Rem實現移動端適配

移動端適配

  • web頁面跑在手機端(h5頁面)
  • 跨平臺
  • 基於webview()
  • 基於webkit

常見適配方法

  • pc端採用display:inline-block,讓div盒子橫着排
  • 移動web:採用定高,寬度百分比,flex彈性佈局,meDIA QUERY 媒體查詢css

  • 媒體查詢
    結合css,經過媒體類型(screen、print)和媒體參數(max-width)html

    @media screen and (max-width: 320px){
              /* css在屏幕跨度<=320px時這段樣式生效 */
              .inner{
                  float: left;
              }
          }
          @media screen and (min-width: 321px){
              .inner{//
              }
          }

以上實現了一個簡單的橫排和豎排的響應node

  • rem原理與簡介
    Rem就是一個字體單位,相似於px,
    區別:他會根據HTML根元素大小而定,同時也能夠做爲高度和寬度的單位。
    適配原理:動態修改html的font-size適配;rem是經過不一樣屏幕的大小設置html根元素的font-size的屬性大小來實現適配。web

    /* +_media實現*/
      @media screen and (max-width: 360px) and (min-width: 321px){
          html{
              font-size: 20px;
          }
      }
      @media screen and (max-width: 320px){
          html{
              font-size: 24px;
          }
      }

經過JS動態設置font-size:瀏覽器

//獲取視窗寬度
    let htmlWidth = document.documentElement.clientWidth || document.body.clientWidth;
        console.log(htmlWidth);
    let htmlDom = document.getElementsByTagName('html')[0];
        htmlDom.style.fontSize = htmlWidth/10 + 'px';
rem進階
  • rem基準值計算sass

    1rem = 16px
  • rem數值計算與構建iphone

    170/16 = 170px
  • rem與scss結合使用(node-sass安裝)
    也能夠直接安裝sass(安裝教程http://www.cnblogs.com/yehui-mmd/p/8035170.html)
  • rem適配實戰
    經過監聽瀏覽器視口來進行適配函數

    let htmlDom = document.getElementsByTagName('html')[0];
      window.addEventListener('resize', (e)=>{
          //獲取視窗寬度
          let htmlWidth = document.documentElement.clientWidth || document.body.clientWidth;
          htmlDom.style.fontSize = htmlWidth/10 + 'px';
      })

    定義rem適配的函數及使用(sass語法)佈局

    @function px2rem($px) {
        $rem:37.5px;//iphone6
        @return ($px / $rem) + rem;
    }
    .header{
        width:100%;
        height: px2rem(40px);
        background-color: red;
        padding-left: px2rem(23px);
     }
相關文章
相關標籤/搜索