Sub topic 9
What containment changes: containing blocks, stacking contexts, clipping
This chapter assumes you know CSS positioning, z-index, and overflow. Containment gives the browser its guarantees by changing how an element behaves. Three of those changes can break a page that looked fine before.
Side effects by containment type
| Value | New containing block for `absolute` and `fixed` descendants | New stacking context | Clips overflow | Independent formatting context |
|---|---|---|---|---|
| `layout` | Yes | Yes | No | Yes |
| `paint` | Yes | Yes | Yes | Yes |
| `size` | No | No | No | No |
| `style` | No | No | No | No |
Size and style containment have no visual side effects. Size containment can still collapse the element to zero, as the size containment chapter covers. The rest of this chapter covers layout and paint, and strict and content include both.
A new containing block
An absolute descendant normally positions against the nearest ancestor with a position other than static. A fixed descendant normally positions against the viewport. With contain: layout or contain: paint, the contained element takes over that role for both.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Fixed inside containment</title>
<style>
.panel {
contain: layout;
width: 300px;
height: 200px;
margin: 100px;
background: #eef;
}
.badge {
position: fixed;
top: 0;
right: 0;
background: gold;
}
</style>
</head>
<body>
<div class="panel">
<span class="badge">New</span>
</div>
</body>
</html>The badge sits in the top-right corner of .panel, not the viewport. It also scrolls with the panel. Remove the contain line and it jumps back to the window corner.
A new stacking context
Both values also create a stacking context. A z-index on a descendant now competes only inside that context. A tooltip with z-index: 9999 inside a contained card cannot rise above a sibling card that comes later in the page.
Clipping
contain: paint clips descendants to the element's padding box. Dropdown menus, focus rings, and box shadows that extend past the edge are cut off. contain: layout does not clip, but it keeps floats and margins from escaping the element.
.card {
contain: paint;
}
.card .menu {
position: absolute;
top: 100%; /* hangs below the card, so it is clipped */
}Common errors
- A
position: fixedbanner or modal sits inside a contained ancestor and no longer covers the viewport. - A tooltip or menu is cut off after you add
contain: paintorcontain: strict. - A
z-indexthat worked before has no effect against elements outside the contained subtree.
Exercise
A position: fixed toolbar sits inside a div with contain: layout. Where does the toolbar position against, and how do you restore viewport positioning?
Show answer
It positions against the div, because layout containment makes the div the containing block for fixed descendants. To restore viewport positioning, remove containment from that ancestor or move the toolbar outside it.