css|面试常常提到的盒🎁🎁模型

120 阅读1分钟

1.两种盒子模型

标准盒模型
box-sizing:content-box 定义一个div盒子,width:200px;height:200px;如果有padding,border那么眼睛看到的盒子大小不是200 * 200 的。因为盒子的宽度包括 内容+padding+border 总结: padding和border不包括在定义的width中 盒子实际宽度 = 定义宽度+padding+border

IE盒模型
box-sizing:border-box 定义一个div盒子,width:200px;height:200px;如果有padding,border那么眼睛看到的盒子大小就是200 * 200 的。因为盒子的宽度就是200,内容区域会被压缩,压缩的内容+padding+border=200 总结: padding和border包含在定义的width中 盒子实际宽度= 定义宽度

2.相同的代码,产生的不同的结果

   <style>
        .div1 {
            width: 200px;
            height: 200px;
            background-color: aquamarine;
            border: 2px solid deeppink;
            padding: 20px;
            margin: 20px; // 默认是标准盒模型
        }

        .div2 {
            width: 200px;
            height: 200px;
            background-color: cadetblue;
            border: 2px solid deeppink;
            padding: 20px;
            margin: 20px;
            box-sizing: border-box; // 设置盒模型是ie
        }
    </style>
</head>

<body>
    <div class="div1">标准盒子</div>
    <div class="div2">怪异盒子</div>
</body>

image (6).png

3.W3C的标准盒模型(标准盒子)和IE盒模型(怪异盒子)对比

image (7).png

image (8).png