To understand the concept of the "Containing Block," we first need to understand how each HTML element is rendered within the document tree.
Every element, whether a paragraph tag, an image tag, or any other, is surrounded by a box. Essentially, HTML is constructed from these boxes.
In other words, the website is built upon boxes.
These boxes are:
- Margin box
- Border box
- Padding box
- Content box
Among those boxes, padding box and content box are the most important things in the Containing Block.
So what is the containing block? It simply means the nearest parent.
<div>
<h1> Heading 2 </h2>
</div>
In this example, the <div>
is the closest parent of the <h1>
, making it the containing block.
Easy, right? Sorry, I lied—it's not that simple.
To determine the containing block, you’ll need to follow these four rules.
- For the element with
static
,relative
orsticky
position, the containing block of that element is straightforward, as mentioned above and is contained within the context box. - For the element with
fixed
position, the containing block of that element is Viewport. - For the element with
absolute
position, then its containing block will be the positioned element withrelative
,sticky
,absolute
,fixed
. It won’t consider non-positioned elements withstatic
as its containing block, even if they’re closer in the HTML structure. And it is contained within the padding box. - The fourth rule is the trickiest and can really complicate things. For elements with
absolute
orfixed
positioning, there's an extra rule to consider: certain CSS properties (listed below) can alter which element acts as the containing block.
- A
filter
,backdrop-filter
,transform
, orperspective
value other thannone
. - A
contain
value oflayout
,paint
,strict
orcontent
(e.g.contain: paint;
). - A
container-type
value other thannormal
. - A
will-change
value containing a property for which a non-initial value would form a containing block (e.g.filter
ortransform
). - A
content-visibility
value ofauto
.
Technically, yes, it can be written this way, and the element with position: fixed
or position: absolute
will be contained within the specified element with those certain properties.
Example 1
<div style="filter: greyscale(1);">
<div style="position: absolute"></div>
</div>
Example 2
<div style="filter: greyscale(1);">
<div style="position: absolute"></div>
</div>
Example 3
<div style="will-change: transform;">
<div style="position: absolute"></div>
</div>