写移动端项目时,总是会纠结是用css3 media query 还是用rem。移动端框架挺多,但是因为项目都比较小,不考虑使用。
无意在网上找到一个移动端rem布局的解决方案,经个人实践,目前未出现什么大问题,收藏备用。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>移动端rem布局</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0" /> <style> .test{ width: 1rem; height: 1rem; background-color: #fa5275; } </style> </head> <body> <div class="test"></div> <p>设置前html的fontsize:16px;</p> <p>设置前html的fontsize:16px;</p> <script> function adapt(designWidth, rem2px){ var d = window.document.createElement('div'); d.style.width = '1rem'; d.style.display = "none"; var head = window.document.getElementsByTagName('head')[0]; head.appendChild(d); var defaultFontSize = parseFloat(window.getComputedStyle(d, null).getPropertyValue('width')); d.remove(); document.documentElement.style.fontSize = window.innerWidth / designWidth * rem2px / defaultFontSize * 100 + '%'; var st = document.createElement('style'); var portrait = "@media screen and (min- "+window.innerWidth+"px) {html{font-size:"+ ((window.innerWidth/(designWidth/rem2px)/defaultFontSize)*100) +"%;}}"; var landscape = "@media screen and (min- "+window.innerHeight+"px) {html{font-size:"+ ((window.innerHeight/(designWidth/rem2px)/defaultFontSize)*100) +"%;}}" st.innerHTML = portrait + landscape; head.appendChild(st); return defaultFontSize; } var defaultFontSize = adapt(640, 100); </script> </body> </html>