Sub topic 4
Layout containment
This chapter covers contain: layout: what it guarantees, what it changes, and where it causes surprises. It assumes you know the box model, positioning, and block and inline layout. It also assumes you have used browser DevTools. Earlier chapters introduced the rendering pipeline and the idea of containment. Here we look at one containment type in detail.
What layout containment promises
Layout is the step where the browser computes the size and position of every box. Normally a change in one place can force the browser to recompute boxes elsewhere. A new child can push siblings down. A changed width can reflow text in a distant ancestor.
contain: layout makes a promise to the browser about one element:
- Nothing inside the element affects the layout of anything outside it.
- Nothing outside the element affects the layout of its contents.
.widget {
contain: layout;
}With that promise, the browser can limit relayout work to the subtree when something inside .widget changes. It does not need to walk up and across the rest of the page to check for effects.
Layout containment does not fix the size of the element. The element's own box is still sized by its contents, and its box still takes part in the outer layout. Only the internal layout is isolated. If you also want the outer size to be independent of the contents, that is size containment, covered in a later chapter.
What the browser changes to keep the promise
The promise is only possible if the browser enforces some rules. Applying contain: layout changes how the element behaves in four ways.
- It becomes a containing block for descendants. This applies to absolutely positioned and fixed-position descendants. Normally an
position: absolutechild looks up the tree for the nearest positioned ancestor. With layout containment, the contained element is that ancestor even if it hasposition: static. - It creates a stacking context. The
z-indexvalues of descendants are resolved inside the element. A child withz-index: 9999cannot rise above a sibling of the contained element. - It becomes an independent formatting context. Margins of children do not collapse through its edges, and floats inside it do not escape it. In practice this is similar to what
display: flow-rootgives you. - Overflowing content is not made to affect outer layout. Descendants that overflow still paint (unless paint containment is also set), but they do not contribute to the scrollable overflow of ancestors in the way they otherwise would. Specifically, ink overflow is not clipped, while the layout of ancestors ignores what happens inside.
The first two are the ones that most often change what you see on screen.
Fixed-position descendants
A position: fixed element is normally placed relative to the viewport. Inside a layout-contained element, it is placed relative to that element instead.
<div class="widget">
<div class="toast">Saved</div>
</div>
<style>
.widget {
contain: layout;
width: 300px;
height: 200px;
border: 1px solid #888;
}
.toast {
position: fixed;
bottom: 0;
right: 0;
}
</style>Without contain: layout, the toast sits in the bottom-right corner of the browser window. With it, the toast sits in the bottom-right corner of .widget. This is the same behavior you get from transform or filter on an ancestor, and it is a common source of "my modal is in the wrong place" bugs.
Stacking
Suppose a dropdown menu inside a contained component uses z-index: 100. A sticky header outside the component uses z-index: 10. Normally the dropdown would cover the header. With layout containment on the component, the component forms a single stacking context. The dropdown's z-index only orders it against other things inside the component. Whether it covers the header depends on the component's own stacking position, which is auto (level 0) unless you set a z-index on it.
Other effects worth knowing
- Baselines. A contained element's baseline is not taken from its contents. In inline or flex layouts that align on baselines, the element may line up differently than before. Check inline-block widgets that contain text.
- Forced line breaks. Inside the element, the browser treats the box as having no influence on how text outside it wraps. Floats from outside do not intrude into the element, and floats inside do not leak out.
- Counters and quotes. Layout containment alone does not isolate
counter-incrementvalues. That is the job of style containment, a separate chapter.
When to use it
Layout containment pays off for components whose internals change often but whose outer position is independent of those changes. Typical cases:
- A live widget, such as a chart, ticker, or chat panel, that updates many times per second.
- A list item in a long list, where editing one item should not trigger layout on the others.
- A third-party embed whose internal styles you do not control.
It helps less on small, static elements. Browsers already optimize many simple layouts, so adding contain there rarely produces a measurable gain. Measure first (a later chapter covers this).
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| A fixed or absolute child jumps to a new position | The contained element is now its containing block | Move the child outside, or set the offsets relative to the container |
| A dropdown is hidden behind outside content | The element created a stacking context | Raise the `z-index` of the contained element, or move the dropdown out of it |
| Margins of a first child no longer collapse with the parent | The element is a new formatting context | Add padding or margin explicitly on the container |
| Items in a flex row line up differently | The baseline changed | Use `align-items` other than `baseline`, or align explicitly |
Checking the effect
Apply the property and inspect it in DevTools. In the Elements panel, the computed styles show contain: layout. Toggle the declaration off and on and watch whether positioned descendants move. If they do, you have a containing-block dependency that you should handle deliberately.
Exercises
Exercise
A page has .panel { contain: layout; }. Inside it, .help uses position: fixed; top: 0; left: 0;. Where does .help appear, and why?
Show answer
It appears at the top-left corner of .panel, not the viewport. Layout containment makes .panel the containing block for fixed-position and absolutely positioned descendants.
Exercise
You add contain: layout to a card, and a tooltip inside it, with z-index: 500, now appears behind a neighboring card. Give the cause and one fix.
Show answer
Layout containment gives the card its own stacking context, so the tooltip's z-index only counts inside the card. The neighboring card, later in the page, paints above the whole contained card. One fix is to give the contained card a higher z-index and a non-static position. Another is to render the tooltip outside the card.