关于CSS盒子模型的总结

102 阅读2分钟

     本文搬运的是我自己的博客,有兴趣可以移步至:CSS盒子模型

     所有的HTML标签都是可以看作一个盒子。CSS盒子模型本质是一个盒子,用于封装其中的HTML元素。盒子模型包括了外边距(margin)、外边框(border)、内边距(padding)、盒子内容(content)四个部分。如下图:

image-20230516102645046.png

     CSS的盒子模型分为两种:标准盒子模型(content-box)怪异盒子模型(border-box),通过box-sizing来控制盒子模型的种类。

标准盒子模型

     标准盒子模型是W3C提出的一种盒子模型标准。box-sizing默认值就是content-box(即标准盒子模型)。它规定盒子的宽(width)、高(height)代表盒子内容部分(content)的宽高。例如下面代码,这个div标签是一个标准盒子模型,我们设置了它的宽高均为400px:

  • width/height = content宽高不包含border和padding;
  • 元素的大小由widthhegihtborderpadding共同决定;

     这就是标准盒子模型,盒子的widthheight属性值定义了盒子内容的大小。盒子的paddingborder都不包含在widthheight

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>box-sizing</title>
    <style>
        .box{
            width: 400px;
            height: 400px;
            margin: 20px;
            border: 2px solid #fff;
            padding: 30px;
            background-color: bisque;
        }
    </style>
</head>
<body>
    <div class="box"></div>
</body>
</html>

     从下面这张图我们可以看到我们设置的widthheight属性都是content的宽高

image-20230516104214027.png

怪异盒子模型

     怪异盒子模型也可以称之为IE盒子模型。我们可以通过box-sizing: border-box;将一个盒子转换为怪异盒子模型。怪异盒子模型中:

  • 元素的widthheight不仅仅包含了content,还包含了borderpaddingwidthheightborderpadding共同决定了content内容的大小;
  • 元素的大小仅由widthheight决定。

     我们现在将上面的例子转换成为怪异盒子模型:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>box-sizing</title>
    <style>
        .box{
            box-sizing: border-box;
            width: 400px;
            height: 400px;
            margin: 20px;
            border: 2px solid #fff;
            padding: 30px;
            background-color: bisque;
        }
    </style>
</head>
<body>
    <div class="box"></div>
</body>
</html>

     可以看到,这里contentborderpadding的宽度之和或者高度之和才等于width或者heigth

image-20230516154452998.png

实际应用

     在开发过程中,我们会碰见子盒子因为paddingborder而超出了子盒子。此时就可以使用box-sizing: border-box;来解决这种问题。