em&rem

144 阅读1分钟

em

相对于当前元素的 font-size

div {
   font-size: 20px;
   width: 2em; // 相当于40px
}

rem

相对于根元素 <html> 的 font-size

应用: 移动端屏幕适配

rem()
window.onresize = () => rem()
function rem () {
    let htmlWidth = document.documentElement.clientWidth || document.body.clientWidth;
    if (htmlWidth>750) htmlWidth=750
    let htmlDom = document.getElementsByTagName('html')[0];
    htmlDom.style.fontSize= (htmlWidth/375)*50 + 'px';
}

公式

当前屏幕的宽度设计稿的宽度=当前屏幕的rem设计稿rem``` \frac{当前屏幕的宽度}{设计稿的宽度}=\frac{当前屏幕的rem值}{设计稿rem值} ```

举例

// 如果设计稿宽度为750
htmlDom.style.fontSize= (htmlWidth/750)*100 + 'px'     
// 如果设计高宽度为375
htmlDom.style.fontSize= (htmlWidth/375)*100 + 'px'

为什么要 1rem = 100px ?
为了方便计算
例如: 设计稿宽度 750px , 1rem = 100, 一个圆的直径是60px, 那么就相当于 0.6rem

为什么不是 1rem = 1px ?
因为字体的最小值为 12px

vw/vh

  • 50vw 屏幕宽度的 50%
  • 50vh 屏幕高度的 50%

px

像素,基本单位

%

width: 50%. 父元素宽度的50%