面试官:「盒模型」

106 阅读1分钟

css中盒模型的介绍?

CSS3 中的盒模型有以下两种:标准盒模型、IE(替代)盒模型。

两种盒子模型都是由 content + padding + border + margin 构成,其大小都是由 content + padding + border 决定的,但是盒子内容宽/高度(即 width/height)的计算范围根据盒模型的不同会有所不同:

  • 标准盒模型:只包含 content 。
  • IE(替代)盒模型:content + padding + border 。

可以通过 box-sizing 来改变元素的盒模型:

  • box-sizing: content-box :标准盒模型(默认值)。
  • box-sizing: border-box :IE(替代)盒模型。

标准盒模型和IE盒模型的区别?

默认情况下是标准盒模型

.box{
    width: 100px;
    height: 100px;
    border: 1px solid #000;
    margin: 10px;
    padding: 20px;
    /* box-sizing: border-box; */
    background-color: aqua;
  }

盒模型在浏览器中的占据的空间是 ( width/height) + padding + border

image.png

当元素设置成IE盒模型的时候

.box{
    width: 100px;
    height: 100px;
    border: 1px solid #000;
    margin: 10px;
    padding: 20px;
    box-sizing: border-box;
    background-color: aqua;
  }

此时盒模型将之前的 (padding + border)计算在宽度和高度中,在浏览器中占据的空间变小了。

image.png