CSS3中新的单位"rem"的坑

<!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>

 

posted @ 2015-08-11 17:54  shusiwei  阅读(3171)  评论(0编辑  收藏  举报