动态REM

141 阅读1分钟

使用 JS 动态调整 REM

让 html 的 font-size == page width 如何做呢?
使用 JS 来做, 设置JS使 font-size == page width ,正因为 rem 是依赖 font-size 的,设置后那就会间接依赖宽度

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

上面的代码表示 1rem == html font-size == 1 page width

优化

  1. 使用 meta viewport
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
  1. 从 pageWidth 来找答案

font-size = pageWidth/100

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

但是这个的 font-size 可能是一个 <10 的值(320/100),在 Chrome 里会有问题(最小12px)
于是再次优化 font-size = pageWidth/10

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

但是这个会带来 1px 的问题
假设屏宽 640px, 1px => (1/640) * 10 = 0.015rem,计算得出它比 1px 还要小 那么该如何解决? 自己写 1px 就行 就不要去换算 rem 了, 字体的写成 font-size: 16px,rem 和 px可以混用

px 自动变为 rem

使用SCSS

如何使用命令行部署 SCSS

  • npm config set registry registry.npm.taobao.org/
  • touch ~/.bashrc
  • echo 'export SASS_BINARY_SITE="npm.taobao.org/mirrors/nod… >> ~/.bashrc
  • source ~/.bashrc
  • npm i -g node-sass
  • mkdir ~/Desktop/scss-demo
  • cd ~/Desktop/scss-demo
  • mkdir scss css
  • touch scss/style.scss
  • start scss/style.scss
  • node-sass -wr scss -o css

编辑 scss 文件就会自动得到 css 文件

如何添加 SCSS

在 scss 文件里添加

@function px( $px ){
  @return $px/$designWidth*10 + rem;
}

$designWidth : 640; // 640 是设计稿的宽度

.child {
  width: px(320);
  height: px(160);
  margin: px(40) px(40);
  border: 1px solid red;
  float: left;
  font-size: px(16);
}