Sub topic 1
Why Rendering Work Gets Expensive
Prerequisites
You should know CSS selectors, the box model, positioning, block and inline layout, and overflow. You should also know how to use browser DevTools to inspect a page and record performance.
Why rendering work gets expensive
When a page changes, the browser may need to recalculate styles, run layout, and paint pixels. Layout calculates the size and position of boxes. Paint draws backgrounds, text, borders, and shadows.
A change near the top of a large document can affect many elements below it. A complex widget can also trigger work outside its own boundary. Repeating this work during scrolling, animation, or user input can cause dropped frames.
Containment: telling the browser a subtree is independent
CSS containment lets you declare that part of a document is independent in a specific way. The browser can then limit invalidation and avoid checking unrelated content.
Containment is a performance hint with behavioral consequences. It changes what the browser is allowed to assume about an element and its descendants.
The `contain` property at a glance
The contain property accepts one or more containment types.
| Value | Main guarantee |
|---|---|
| `layout` | Descendant layout does not affect content outside the element |
| `paint` | Descendants are not painted outside the element’s bounds |
| `size` | The element’s size does not depend on its contents |
| `style` | Certain style effects are scoped to the contained subtree |
You can combine values:
.widget {
contain: layout paint;
}Layout containment
Layout containment isolates layout calculations. Changes inside the element do not require the browser to recalculate layout for unrelated content outside it.
.widget {
contain: layout;
}This is useful for independent cards, editors, or dashboard widgets. Check positioning carefully: layout containment can establish a new containing block for positioned descendants. Percentages and position: absolute may therefore resolve differently than expected.
Paint containment
Paint containment keeps descendant drawing inside the element’s border box. Overflowing shadows, positioned children, and other visual effects can be clipped.
.card {
contain: paint;
}Paint containment can also create a stacking context. That may change how the element layers with neighboring elements. Use it only when clipping and stacking behavior are acceptable.
Exercise
Which value should you choose when descendant drawing must stay inside an element’s bounds?
Show answer
Use contain: paint, while checking that clipping and stacking changes are intended.