html文件:rem和html有關 em和當前盒子有關css
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, minimal-ui"> <title>移動端佈局</title> <style type="text/css"> *{ padding: 0; margin: 0; } ul{ list-style: none; } .clearfix:after{ content: ''; display: block; clear: both; } html{ /* font-size: 20px;*/ /*1rem=20px*/ } /* html{ width: 100%; height: 100%; overflow: hidden; }*/ body{ width: 100%; height: 100%; /*overflow: auto;*/ padding-top: 80px; } .head-box{ width: 100%; height: 80px; background-color: red; position: fixed; top: 0; left: 0; z-index: 9999; } .list{ font-size: 14px; } .list .item{ float: left; width: 1rem; height: 1rem; border: 1px solid black; margin: 0.1rem; } /* 移動端單位 相對單位和絕對單位px 相對單位 em:相對於當前盒子的設置的字體; 20px = 1em rem:相對於html的字體大小; */ </style> </head> <body> <header class="head-box"> <div class="head-top"></div> <div class="head-bottom"></div> </header> <ul class="list clearfix"> <li class="item">1111111</li> <li class="item"></li> <li class="item"></li> <li class="item"></li> <li class="item"></li> <li class="item"></li> <li class="item"></li> <li class="item"></li> </ul> <div></div> <div></div> </body> <script src="./resize.js"></script> </html>
js代碼:注意在設置時當前設計的尺寸 和 自定義的換算 width爲當前的尺寸,啓動會自動檢測html
/*得到頁面寬度後動態修改html上的fontsize * 320爲iphone5設計稿下的頁面寬度,以下設置後頁面的頁面在iphone5等寬屏幕上html * 的font-size會變爲20px,即 1rem = 100px 1px=0.05rem * 因此設置元素尺寸的時候,若是測量設計稿 15px 則需設置尺寸爲 (0.05*15)rem = 0.75rem */ // 1rem = 100px 1px = 0.01rem !(function(doc, win) { var docEle = doc.documentElement, evt = "onorientationchange" in window ? "orientationchange" : "resize", fn = function() { var width = docEle.clientWidth; console.log(width) width && (docEle.style.fontSize =100 * (width / 1226) + "px"); }; win.addEventListener(evt, fn, false); doc.addEventListener("DOMContentLoaded", fn, false); }(document, window));