vw rem 根据页面宽度来设置根字号
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no"> <title>Document</title> <style> html,body{ font-size:13.33333333vw; } @media screen and (min-width :750px){ html,body{ font-size:100px; background-color:skyblue; } } @media screen and (max-width :320px){ html,body{ font-size:42.666666px; background-color:pink; } } body{ max-width:750px; margin:auto; background-color: #eee; } .fs{ width:100rem; font-size: 0.24rem; } </style> </head> <body> <div class="fs">主题</div> </body> </html>
原理:
(function(doc, win) { var docEl = doc.documentElement, resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize', recalc = function() { var clientWidth = docEl.clientWidth; if(!clientWidth) return; if(clientWidth >= 750) { docEl.style.fontSize = '100px'; } else { //docEl.style.fontSize = 100 * (clientWidth / 640) + 'px'; docEl.style.fontSize = clientWidth / 7.5 + 'px'; } }; if(!doc.addEventListener) return; win.addEventListener(resizeEvt, recalc, false); doc.addEventListener('DOMContentLoaded', recalc, false); })(document, window);