学习CSS布局

box-sizing

人们慢慢的意识到传统的盒子模型不直接,所以他们新增了一个叫做 box-sizing 的CSS属性。

当你设置一个元素为 box-sizing: border-box; 时,此元素的内边距和边框不再会增加它的宽度。

这里有一个与前一页相同的例子,唯一的区别是两个元素都设置了 box-sizing: border-box; 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>box-sizing</title>
    <style>
        /** {
            box-sizing: border-box;
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            -ms-box-sizing: border-box;
            -o-box-sizing: border-box;
        }*/

        .simple {
            width: 400px;
            height: 200px;
            border: 1px solid red;
            margin: 20px auto;

            box-sizing: border-box;
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            -ms-box-sizing: border-box;
            -o-box-sizing: border-box;
        }
        .fancy {
            width: 400px;
            height: 200px;
            border: 1px solid red;
            margin: 20px auto;
            padding: 50px;

            box-sizing: border-box;
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            -ms-box-sizing: border-box;
            -o-box-sizing: border-box;
        }
    </style>
</head>
<body>
    <div id="simple" class="simple">我是simple</div>
    <div id="fancy" class="fancy">我和simple一样大了</div>

    <script>
        var oDiv1 = document.querySelector('#simple');
        console.log(oDiv1.offsetWidth, oDiv1.offsetHeight);
        var oDiv2 = document.querySelector('#fancy');
        console.log(oDiv2.offsetWidth, oDiv2.offsetHeight);
    </script>
</body>
</html>

结果:

既然没有比这更好的方法,一些CSS开发者想要页面上所有的元素都有如此表现。

所以开发者们把以下CSS代码放在他们页面上:

* {
            box-sizing: border-box;
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            -ms-box-sizing: border-box;
            -o-box-sizing: border-box;
        }

这样可以确保所有的元素都会用这种更直观的方式排版。

不过 box-sizing 是个很新的属性,目前你还应该像我上面例子中那样使用 -webkit-和 -moz- 前缀。

这可以启用特定浏览器实验中的特性。同时记住它是支持IE8+的。

 

原文地址:http://zh.learnlayout.com/box-sizing.html

原文地址:https://www.cnblogs.com/sorrowx/p/6801502.html