学习CSS布局

盒模型

在我们讨论宽度的时候,我们应该讲下与它相关的另外一个重点知识:盒模型

当你设置了元素的宽度,实际展现的元素却超出你的设置:

这是因为元素的边框和内边距会撑开元素。

看下面的例子,两个相同宽度的元素显示的实际宽度却不一样。

 

看看代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>盒模型</title>
    <style>
        .simple {
            width: 400px;
            height: 200px;
            border: 1px solid red;
            margin: 20px auto;
        }

        .fancy {
            width: 400px;
            height: 200px;
            border: 1px solid red;
            margin: 20px auto;
            padding: 10px;
        }
    </style>
</head>
<body>
   <div id="simple" class="simple">
       我小一些哦
   </div>
   <div id="fancy" class="fancy">
       我比他大点
   </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>

根据输出来的结果,或者盒子模型就知道,offsetWidth就是自身宽度+border的宽度+padding的内边距,高度同理。

以前有一个代代相传的解决方案是通过数学计算。

CSS开发者需要用比他们实际想要的宽度小一点的宽度,需要减去内边距和边框的宽度。

值得庆幸地是你不需要再这么做了...

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

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