工作生活

动态 REM

2019-07-01  本文已影响0人  lyp82nkl

什么是 REM ?

说到rem自然就会想到em,我们知道em是相对于父元素的字体大小的单位,那么rem则是相对于根元素也就是<html>元素的字体大小的单位。

CSS中常用的长度单位:

em 和 rem 的区别

html{
  font-size:32px;
}
body{
  border:1px solid red;
  font-size:16px;
  height:2em; 
  /*此时高度为32px*/
  height:2rem;
  /*此时高度为64px*/
}

为什么要使用动态REM技术

动态REM的使用

 var pageWidth = window.innerWidth
 document.write('<style>html{font-size:'+pageWidth+'px;}</style>')

即让<html></html>的font-size = 设备宽度,即 1 rem = 1 pageWidth
然后在css中,就可以优雅的使用rem作为单位啦。

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

栗子:

body {
  font-size: 16px
}
.content {
  background: #ddd;
  margin: 10px 0;
}
.content {
  float: left;
  width: 0.4rem;            /* 128(div的宽度) / 320(设计稿屏幕的宽度) = 0.4rem */
  height: 0.2rem;           /* 0.4rem的一半 = 0.2rem  =  设计稿的 64px */
  margin: 0.05rem 0.05rem;  /* 0.2rem 的一半为 0.1rem => 32px */
                            /*因为设计稿为16px,所以再 0.1rem的一半 0.05rem*/
}

然而这么写有点不对劲呀,每个长度的数值都是用好几位小数来表示,看着不太爽,或许可以让100 rem = 1 pageWidth,比如margin就可以改写成margin: 5rem 5rem; 看起来貌似舒服多了。

但是!!每个长度都要去计算,如果css多的话那么工作量就会很大,所以使用scss让px自动转化成rem。

使用scss让px自动转化成rem

安装scss(Mac用户)
// 使用淘宝镜像
$ npm config set registry https://registry.npm.taobao.org/   

$ touch ~/.bashrc

$ echo 'export SASS_BINARY_SITE="https://npm.taobao.org/mirrors/node-sass"' >> ~/.bashrc

$ source ~/.bashrc

$ npm i -g node-sass
使用PX2REM
//在当前文件新建scss和css文件夹
$ mkdir scss css  

//新建style.scss 文件
$ touch scss/style.scss 

//重点
$ node-sass -wr scss -o css

css:

//在style.scss写入 

//重点
@function px($px) {
  @return $px / $designWidth * 10 + rem;
  //注意这里的10是为了省小数点,对应script
}

$designWidth: 320;   //设计师给你设计稿的宽度

* {
  margin: 0;
  padding: 0;
}

body {
  font-size: 16px
}
.content {
  background: #ddd;
  margin: 10px 0;
}
.content {
  float: left;
  width: px(128);  // 128 / 320 * 10 = 4rem
  height: px(64);
  margin: px(16);
}
.clearfix::after {
  content: '';
  display: block;
  clear: both;
}

js:

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

<script>
  var pageWidth = window.innerWidth
  document.write('<style>html{font-size:' + pageWidth/10 + 'px}</style>')
</script>
上一篇 下一篇

猜你喜欢

热点阅读