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:

  1. Margin box
  2. Border box
  3. Padding box
  4. 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.

  1. For the element with static , relative or sticky position, the containing block of that element is straightforward, as mentioned above and is contained within the context box.
  2. For the element with fixed position, the containing block of that element is Viewport.
  3. For the element with absolute position, then its containing block will be the positioned element with relative , sticky , absolute , fixed . It won’t consider non-positioned elements with static as its containing block, even if they’re closer in the HTML structure. And it is contained within the padding box.
  4. The fourth rule is the trickiest and can really complicate things. For elements with absolute or fixed positioning, there's an extra rule to consider: certain CSS properties (listed below) can alter which element acts as the containing block.

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>