XiZev / blog

record my learning of font-end
0 stars 0 forks source link

手机屏幕自适应之 rem #4

Open XiZev opened 3 years ago

XiZev commented 3 years ago

引入

在所有现代浏览器中,其默认的字体大小就是“16px”,所有未经调整的浏览器都符合: 1em=16px

em

是相对长度单位。相对于当前对象内文本的字体尺寸。如果当先元素设置 字体的font-size,则会继承父元素的大小。

<style>
.div1 {
   background:red;
   font-size:100px;
   width:1em;
   height:1em;
   margin-bottom:0.5em;
}
.div2 {
   background:blue;
   font-size:200px;
   width:1em;
   height:1em;
}
</style>
<div class="div1"></div>
<div class="div2"></div>

QQ截图20210327164757

可以看出宽、高同样设置成1em* 1em 的两个元素,它们表现出来的大小却不一样,原因是em的大小由元素内部的font-size决定。

div1:1em = 100px ;div:1em = 200px。

rem

rem是CSS3新增的一个相对单位(root em,根em),与em相比,相对的只是HTML根元素。通过它既可以做到只修改根元素就成比例地调整所有字体大小,又可以避免字体大小逐层复合的连锁反应。

html {
   font-size:16px;
 }
//1rem相当于16px

设置rem的方法:

//640px宽度屏幕1rem = 20px,其他任意屏幕等比例放大缩小 1rem=  (screen_w/ 640) * 20;
    (function(){
      var screen_w = document.documentElement.clientWidth;
      var screen_h = document.documentElement.clientHeight;
      var fontSize = (screen_w / 640) * 20;
      var style = document.createElement('style');
      style.type = 'text/css';
      style.innerHTML = 'html{font-size:' + fontSize + 'px}';
      document.getElementsByTagName('head').item(0).appendChild(style);
    })();
@media screen  and (max-width: 750px){
    html {
        font-size:30px;
    }
}
@media screen and (min-width:640px) and (max-width:749px){
    html {
        font-size:25px;
    }
}
@media screen and (min-width:480px) and (max-width:639px){
    html { 
        font-size:20px; 
    }
}
@media screen and (min-width:320px) and (max-width:479px){
    html {
        font-size:15px;
    }
}