移動端適配(實現爲主)

此次文章主要是已實現爲主,原理已經有許多大佬的文章博文了css

移動端開發標籤

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">

rem原理

經過設置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

@media實現html的fontSize設置
@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
純css實現

移動端使用rem佈局須要經過JS設置不一樣屏幕寬高比的font-size,結合vw單位和calc()可脫離JS的控制iphone

/* 基於UI width=750px DPR=2的頁面 */
html {
    font-size: calc(100vw / 7.5);
}
jq實現(保存大屏幕爲100px)
$(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;
阿里flexible適配
npm i -S amfe-flexible

vw適配(百分比適配)

配置後直接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`
    }
  }
}

相關博文

https://www.cnblogs.com/azhai...post

相關文章
相關標籤/搜索