移动端自适应rem布局
2018-08-11 本文已影响55人
安逸的蓝鲸
简谈工作中 使用的的两种常见的rem布局方案
方案1:采用媒体查询,缺点:只能适配主流机型,不够全面
在base.css文件中设置媒体查询,对于不同的设备宽度,给根元素即htm设置不同的大小
@media screen and (max-width: 1440px) { html {font-size: 150px !important;} }
@media screen and (max-width: 1080px) { html {font-size: 150px !important;} }
@media screen and (max-width: 1024px) { html {font-size: 142px !important;} }
@media screen and (max-width: 980px) { html {font-size: 136px !important;} }
@media screen and (max-width: 750px) { html {font-size: 104px !important;}}
@media screen and (max-width: 720px) { html {font-size: 100px !important;} }
@media screen and (max-width: 640px) { html {font-size: 88.88px !important;} }
@media screen and (max-width: 540px) { html {font-size: 75px !important;} }
@media screen and (max-width: 480px) { html {font-size: 66.66px !important;} }
@media screen and (max-width: 432px) { html {font-size: 60px !important;} }
@media screen and (max-width: 414px) { html {font-size: 57.5px !important;} }
@media screen and (max-width: 400px) { html {font-size: 55.55px !important;} }
@media screen and (max-width: 393px) { html {font-size: 54.5px !important;} }
@media screen and (max-width: 375px) {html {font-size: 52.08px !important;}}
@media screen and (max-width: 360px) { html {font-size: 50px !important;} }
@media screen and (max-width: 320px) { html {font-size: 44.44px !important;} }
@media screen and (max-width: 240px) { html {font-size: 33.33px !important;} }
方案2:动态计算根元素的大小,比较精准,
(function () {
window.onresize = function(params) {
var html = document.querySelector("html");
var rem = html.offsetWidth / 7.5; //分母为7.5表示以750px的设计稿为准,方便计算,亦可自定
html.style.fontSize = rem + "px";
};
window.onresize();
})();