learning-note icon indicating copy to clipboard operation
learning-note copied to clipboard

移动端布局 rem + sass

Open jackPanyj opened this issue 8 years ago • 1 comments

这是我自己项目中用的移动端布局的适配方案:

主要采用了 rem + sass

假设设计图给的是 750 x 1334 即 iphone6 的尺寸, 并且有一个宽高都为200px的正方形

首先在html中注入一段js脚本。

  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type="text/javascript">
      // 我喜欢简单粗暴的做法
      // 思路: 将html元素的font-size设置为屏幕宽度的1/20
      // !警告 不要将 document.documentElement.clientWidth
      //  换成 window.innerWidth, 在魅族手机下会出问题
      document.documentElement.style.fontSize = document.documentElement.clientWidth / 20 + 'px'
    </script>
  </head>
  <body>
      <div class="test"></div>
  </body>

scss 的写法

  // 定义函数,让它去帮我自动把px转成rem
  @function r($px) {
    @return $px / (750 / 20) + rem;
  }

  .test {
    width: r(200);
    height: r(200);
  }

html中自定义的脚步可以帮助我们动态的设置根元素的font-size大小,

scss中自定义的函数r会帮助我们自动把px换成rem,

这样就完成了一个简单的移动端布局的响应式方案

jackPanyj avatar Oct 28 '16 05:10 jackPanyj

来捧场~~~

lucas1677 avatar Aug 01 '18 09:08 lucas1677