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,relativeorstickyposition, the containing block of that element is straightforward, as mentioned above and is contained within the context box. - For the element with
fixedposition, the containing block of that element is Viewport. - For the element with
absoluteposition, then its containing block will be the positioned element withrelative,sticky,absolute,fixed. It won’t consider non-positioned elements withstaticas 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
absoluteorfixedpositioning, 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, orperspectivevalue other thannone. - A
containvalue oflayout,paint,strictorcontent(e.g.contain: paint;). - A
container-typevalue other thannormal. - A
will-changevalue containing a property for which a non-initial value would form a containing block (e.g.filterortransform). - A
content-visibilityvalue 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>