我们已知px是固定值像素单位,em是相对于当前父级的字体大小定义的。而rem是根元素的字体大小定义的,相对于前两位,rem是比较好用和使用最多的单位。
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title></title>
6 <style>
7 html{
8 font-size:20px;
9 }
10 #div1{
11 width:16rem;
12 height:300px;
13 background: red;
14 /*可以根据父元素字体大小而改变*/
15 }
16 </style>
17 <script>
18 function change(){
19 //获得根元素的字体大小
20 document.documentElement.style.fontSize=16 * document.documentElement.clientWidth / 320+"px"
21 }change();
22 // change函数添加resize事件
23 window.addEventListener('resize',change,false);
24 </script>
25 </head>
26 <body>
27 <div id="div1"></div>
28 </body>
29 </html>