此次文章主要是已实现为主,原理已经有许多大佬的文章博文了css
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
经过设置html的fontSzie来实现动态rem,其实就是将页面百分比化
好比:html
<html font-size="50px"> <div class="box" width="1.25rem"></div> </html>
html为50px; 能够获得1rem为50px(html被分为100rem)
那么:box的1.25rem宽度就能够获得为(50*1.25)pxnpm
@charset "UTF-8"; @mixin queryWidth($min, $max) { @if $min == -1 { @media screen and (max-width: $max+px) { html { font-size: ( ($max+1) / 375 ) * 100px; } } } @else if $max == -1 { @media screen and (min-width: $min+px) { html { font-size: ( $min / 375 ) * 100px; } } } @else { @media screen and (min-width: $min+px) and (max-width: $max+px) { html { font-size: ( $min / 375 ) * 100px; } } } } @include queryWidth(-1, 319); // for iphone 4 @include queryWidth(320, 359); // for iphone 5 @include queryWidth(360, 374); @include queryWidth(375, 383); // for iphone 6 @include queryWidth(384, 399); @include queryWidth(400, 413); @include queryWidth(414, -1); // for iphone 6 plus
移动端使用rem布局须要经过JS设置不一样屏幕宽高比的font-size
,结合vw单位和calc()可脱离JS的控制iphone
/* 基于UI width=750px DPR=2的页面 */ html { font-size: calc(100vw / 7.5); }
$(window).resize(infinite); infinite(); function infinite() { var htmlWidth = $('html').width(); if (htmlWidth >750) { $("html").css({ "font-size" : "100px" }); } else { $("html").css({ "font-size" : 100 / 750 * htmlWidth + "px" }); } } #body标签 width: 7.5rem;
npm i -S amfe-flexible
配置后直接css写px就会自动解析为vw了布局
# 安装postcss-px-to-viewport: npm install postcss-px-to-viewport --save # postcss.config.js配置: module.exports = { plugins: { autoprefixer: {}, "postcss-px-to-viewport": { viewportWidth: 375, // 视窗的宽度,对应的是咱们设计稿的宽度,Iphone6的通常是375 (xx/375*100vw) viewportHeight: 667, // 视窗的高度,Iphone6的通常是667 unitPrecision: 3, // 指定`px`转换为视窗单位值的小数位数(不少时候没法整除) viewportUnit: "vw", // 指定须要转换成的视窗单位,建议使用vw selectorBlackList: ['.ignore', '.hairlines'],// 指定不转换为视窗单位的类,能够自定义,能够无限添加,建议定义一至两个通用的类名 minPixelValue: 1, // 小于或等于`1px`不转换为视窗单位,你也能够设置为你想要的值 mediaQuery: false // 容许在媒体查询中转换`px` } } }