Sub topic 2
Containment: telling the browser a subtree is independent
This chapter assumes you know CSS selectors, the box model, and positioning. It also assumes you have seen the style, layout, and paint stages of rendering from the previous chapter.
The problem containment solves
By default, the browser assumes any element can affect any other. If you change the text inside a small widget, the browser can't be sure that the page's layout stays the same. It may need to recalculate layout for the whole document, not just the widget.
Containment is a promise you make to the browser. You declare that a subtree is independent of the rest of the page in certain ways. The browser can then limit its work to that subtree and skip the rest.
How the promise works
Here is what happens when something inside a contained element changes:
The promise runs in both directions. Nothing inside the element may affect the outside, and the outside may not affect the inside. The browser trusts you. If your CSS breaks the promise, the browser doesn't raise an error. It enforces the promise instead, and that can change how your page looks.
Your first contained element
You turn the promise on with the contain property:
.widget {
contain: layout;
}With contain: layout, the browser treats .widget as a layout boundary. The descendants' layout can't push or resize anything outside the widget. Layout changes elsewhere on the page also can't reshape the widget's contents.
layout is one of several values you can use. Each one covers a different kind of independence. The next chapters cover them one at a time:
| Containment type | What it isolates |
|---|---|
| layout | How descendants are positioned relative to the rest of the page |
| paint | Where descendants are drawn |
| size | The element's own dimensions |
| style | Certain style effects, such as counters |
Enforcement, not a hint
Containment is not an optimization hint that the browser may ignore. It changes how the element behaves. For example, a contained element can become the containing block for absolutely positioned descendants. It can also create a stacking context. You will see these side effects in detail later. For now, remember that adding contain can change what you see on screen, not only how fast it renders.
Checking your understanding
Exercise
A page has a .comments section whose content updates often. You add contain: layout to .comments. Which two things does this promise the browser about layout?
Show answer
First, nothing inside .comments affects the layout of anything outside it. Second, nothing outside .comments affects the layout of its contents. The browser can therefore limit layout work to the subtree.