大家好,我是 前端架构师 - 大卫。
更多优质内容请关注微信公众号 @程序员大卫。
初心为助前端人🚀,进阶路上共星辰✨,
您的点赞👍与关注❤️,是我笔耕不辍的灯💡。
前言
CSS 包含块(containing block)是一个很重要的概念,用来决定一个元素的位置和大小的参考框。它的定义由元素的父级上下文决定,通常是元素最近的定位祖先(或祖先元素)。
包含块的作用主要体现在以下几个方面:
- 确定相对定位、绝对定位或固定定位元素的参考框。
- 决定宽度和高度使用百分比值时的参考框。
- 确定盒模型(box model)的尺寸计算方式。
包含块的规则
-
普通流中的元素(如静态定位
position: static
或相对定位position: relative
): 包含块是由最近的块级父元素的内容区域决定的。 -
绝对定位元素(
position: absolute
): 包含块是由最近的定位祖先的padding box决定(最近的position
值为relative
、absolute
、sticky
或fixed
的元素)。 -
固定定位元素(
position: fixed
): 包含块是由**视口(viewport)**决定,除非元素位于某些特殊的上下文(如 CSS 中的transform
或will-chang
e 创建的新的包含块)。 -
百分比宽度、高度、外边距和填充: 百分比值基于包含块的对应尺寸。
例子
普通流中的包含块
<div
style="
width: 400px;
height: 300px;
padding: 20px;
border: 10px solid black;
box-sizing: border-box;
"
>
<div style="width: 50%; height: 50%; background: lightblue">子元素</div>
</div>
- 子元素的
width: 50%;
和height: 50%;
基于父元素的内容区域,即400px - 2 * 20px(padding)- 2 * 10(border)
。
绝对定位元素的包含块
<div style="width: 400px; height: 300px; position: relative; border: 1px solid black;">
<div style="position: absolute; left: 50px; top: 50px; width: 100px; height: 100px; background: lightgreen;">
绝对定位元素
</div>
</div>
- 绝对定位的子元素包含块是父元素,因为父元素设置了
position: relative
。
固定定位元素的包含块
<div style="width: 400px; height: 300px; border: 1px solid black;">
<div style="position: fixed; top: 20px; left: 20px; width: 100px; height: 100px; background: pink;">
固定定位元素
</div>
</div>
- 固定定位元素的包含块是视口,它与父元素的
div
无关。
CSS 属性改变包含块
以下属性会创建新的包含块:
transform
(如transform: translate
或scale
)。will-change
。filter
。perspective
。
<div style="width: 400px; height: 300px; transform: scale(1);">
<div style="position: absolute; left: 50%; top: 50%; width: 100px; height: 100px; background: lightcoral;">
新的包含块
</div>
</div>
- 设置
transform
后,父元素创建了新的包含块,绝对定位的子元素会基于它的内容区域计算位置。
总结
通过了解包含块的规则,可以更好地控制元素的布局和位置行为。
End
点赞👍 + 关注➕ + 收藏❤️ = 学会了🎉。
更多优质内容关注公众号,
@前端大卫
。