Skip to content
On this page

包含块

当一个客户端代理(比如说浏览器)展示一个文档的时候,对于每一个元素,它都产生了一个盒子。每一个盒子都被划分为四个区域:

  • 内容区
  • 内边距区
  • 边框区
  • 外边距区

包含块的影响

元素的尺寸及位置,常常会受它的包含块所影响。对于一些属性,例如 width, height, padding, margin,绝对定位元素的偏移值(比如 position 被设置为 absolutefixed),当我们对其赋予百分比值时,这些值的计算值,就是通过元素的包含块计算得来。

position包含块Cool
static、relative、sticky最近的祖先块元素的 内容区inline-block, block 或 list-item 元素
absolute最近的 position 的值不是 static的祖先元素的 内边距区 的边缘,也就是说 top:0,left:0内边距区 的边缘 ⭐--
fixedviewport--

如果 position 属性是 absolute 或 fixed,包含块也可能是由满足以下条件的最近父级元素的内边距区的边缘组成的:

  • ⭐transform 或 perspective 的值不是 none
  • will-change 的值是 transform 或 perspective
  • filter 的值不是 none 或 will-change 的值是 filter(只在 Firefox 下生效)。
  • contain 的值是 paint(例如:contain: paint;)
  • backdrop-filter 的值不是 none(例如:backdrop-filter: blur(10px);)

根据包含块计算百分值

如上所述,如果某些属性被赋予一个百分值的话,它的计算值是由这个元素的包含块计算而来的。这些属性包括盒模型属性和偏移属性:

要计算 height top 及 bottom 中的百分值,是通过包含块的 height 的值。

如果包含块的 height 值会根据它的内容变化,而且包含块的 position 属性的值被赋予 relative 或 static ,那么,这些值的计算值为 auto。(ℹ️默认的 height 为 auto)

要计算 width, left, right, padding, margin 这些属性由包含块的 width(即内容块) 属性的值来计算它的百分值。

html
<style>
.BFC-boxSection {
  display: block;
  width: 400px;
  height: 160px;
  background: lightgray;
  overflow:hidden
}

.BFC-boxSection>.BFC-boxP {
  width: 50%;   /* == 400px * .5 = 200px */
  height: 25%;  /* == 160px * .25 = 40px */
  margin: 5%;   /* == 400px * .05 = 20px */
  padding: 5%;  /* == 400px * .05 = 20px */
  background: cyan;
  line-height:initial
}
</style>
<body>
  <section class="BFC-boxSection">
    <p class="BFC-boxP">This is a paragraph!</p>
  </section>
</body>

This is a paragraph!

html
<style>
.BFC-boxSection2 {
  transform: rotate(0deg);
  width: 400px;
  height: 160px;
  background: lightgray;
}

.BFC-boxSection2>.BFC-boxP2 {
  position: absolute;
  left: 80px;
  top: 30px;
  width: 50%;   /* == 200px */
  height: 25%;  /* == 40px */
  margin: 5%;   /* == 20px */
  padding: 5%;  /* == 20px */
  background: cyan;
  line-height:initial
}
</style>
<body>
  <section class="BFC-boxSection2">
      <p class="BFC-boxP2">This is a paragraph!</p>
  </section>
</body>

This is a paragraph!