CSS包含块

CSS 包含块(Containing Block)

什么是包含块

顾名思义,包含块就是包含了当前元素的那个元素。另外,既然叫包含“块”,那么那个元素一定是一个块元素。

包含块有什么用

包含块最主要的作用是,当使用百分比单位时,确定是相对于谁的百分比。

例如,如果一个元素设定了CSS width: 100%,那么这里的100%就是相对于这个元素包含块宽度的100%。

如何确定包含块

确定一个元素的包含块的过程完全依赖于这个元素的 position 属性:

  1. 如果 position 属性为 static 或 relative ,包含块就是由它的最近的祖先块元素(比如说inline-block, block 或 list-item元素)或格式化上下文(比如说 a table container, flex container, grid container, or the block container itself)的内容区的边缘组成的。

  2. 如果 position 属性为 absolute ,包含块就是由它的最近的 position 的值不是 static (也就是值为fixed, absolute, relative 或 sticky)的祖先元素的内边距区的边缘组成。

  3. 如果 position 属性是 fixed,在连续媒体的情况下(continuous media)包含块是 viewport ,在分页媒体(paged media)下的情况下包含块是分页区域(page area)。

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

    1. transfrom 或者 perspective属性不为none的元素。

    2. A will-change value of transform or perspective

    3. A filter value other than none or a will-change value of filter (only works on Firefox).

Author: LeoB_O
Link: https://leob-o.github.io/2019/06/03/CSS-Containing-Block/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.