<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <style type="text/css"> html:root{font-size:62.5%;} body{font-size:.16rem;padding:0;margin:0;} span{font-size:1.6rem;height:10.5rem;width:10.5rem;display:block;background-color:#f60;} @media screen and (min-width:640px){ html:root{font-size:125%;} } </style> <body> <span>不同分辨率可能需要媒體查詢寫幾次</span> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <style type="text/css"> html:root{font-size:625%;} body{font-size:.16rem;padding:0;margin:0;} span{font-size:.16rem;height:1.05rem;width:1.05rem;display:block;background-color:#f60;overflow:hidden;} @media screen and (min-width:640px){ html:root{font-size:1250%;} } </style> <body> <span>不同分辨率可能需要媒體查詢寫幾次</span> </body> </html>
上述代碼中的幾乎是一樣的,唯一的不同就是html:root中的font-size中62.5%與625%的區別,有什么分區呢?
通常情況下,一般瀏覽器中的默認的字體大小應該是16px,html:root中的字體大小就是根據 10 / 16 * 100 = 62.5,由此算來,文中的1.6rem便為16px了,但是有一個問題是必考慮到的,那就是,通常字體大小不支持12px以下的時候,那么就會出現一類問題:width:10rem != 100px(代碼一)。
為了解決這樣一個問題,所以我們則需要把html:root中的font-szie的比例放得更大,以達到讓瀏覽器達到支持12px以下的基本單位的效果,此時width:1rem == 100px(代碼二)。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no"> <title>Document</title> </head> <style type="text/css"> body{font-size:.16rem;padding:0;margin:0;} span{font-size:.16rem;height:1.05rem;width:1.05rem;display:block;background-color:#f60;overflow:hidden;} </style> <body> <span>自動換算html:root的font-size</span> </body> <script type="text/javascript"> ;(function() { var style = document.createElement('style'), sheet, updateUnit = function() { var unit = window.innerWidth / 320 * 625 + '%'; sheet.rules[0].style.fontSize = unit; }; document.head.appendChild(style); sheet = style.sheet; sheet.addRule('html:root'); window.addEventListener('load', updateUnit); window.addEventListener('resize', updateUnit); })(window); </script> </html>
