Understanding CSS Contain

The contain property in CSS tells the browser which parts of the layout are self-contained and can be updated without requiring a full repaint. This is mostly useful when adding and removing content dynamically.

No contain set

When new elements are added, the browser has to figure out what changed. Content can extend out of its container.

contain: layout

The layout outside the container does not affect what’s inside the container and vice-versa. This also creates a new formatting context, so floats are contained and absolutely positioned elements are relative to the container. Content can still extend out of its container.

contain: paint

Nothing inside the container extends outside the container, as if overflow:hidden were applied to the container.

contain: size

The size of the container will not change, even if elements are added and removed. (Don’t use unless you’re specifying a size in CSS!)

contain: content

Combines contain: layout and contain: paint. The layout outside the container does not affect what’s inside the container, and nothing inside the container extends outside.

contain: strict

Combines contain: layout, contain: paint, and contain: size.

BONUS: display: flow-root

Does not affect how the browser recalculates layout, but if you just want a new formatting context, display: flow-root will create one.

References