Skip to content
AITroveRead. Build. Understand.
Make this comfortable

CSS contain: isolate work without cutting off content

Last updated: 5 Oct 20265 min read
tutorial
BeginnerBy AITrove Editorial

The contain property marks aspects of an element's subtree as independent from the surrounding page. Layout containment limits layout interactions; paint containment also clips painting beyond the element's bounds.

When to use it

A case-list row updates its status several times while neighboring rows stay still. Layout containment can give the browser a clearer boundary for those changes, but the row must be a real independent unit. Do not add paint containment if a focus ring, popover, or error message needs to extend beyond the row. Size containment is stronger: the children's sizes no longer determine the container's size, so a row may collapse unless dimensions are supplied. In the sample, only layout containment is requested. Test a long translated status, an expanded details area, and a keyboard-focused action before measuring whether the boundary helps. The declaration can also change containing-block and stacking behavior for positioned descendants; inspect badges that formerly aligned against an outer panel.

css
.case-list__row { contain: layout; padding: 1rem; border-block-end: 1px solid #b7c7d0; }
.case-list__row:focus-within { outline: 2px solid #175b44; outline-offset: 2px; }

Cost and verification

Containment is a performance hint with layout consequences, not a free speed switch. Profile the real list before and after; a small static page may show no useful gain. Paint containment clips overflow, while size containment needs a deliberate sizing contract. Layout containment itself creates a new formatting and stacking context and can alter absolute positioning. Keep the boundary on the smallest independent region and review overlays, print output, and high zoom. If the row's content must affect surrounding layout in a particular way, preserve that behavior instead of forcing isolation.

Common Mistakes

  • Do not use paint containment around a focus ring or escaping menu.
  • Do not apply size containment without a size plan.
  • Do not claim a performance gain without measuring the real page.

Connected lessons

css
reference
web
Storage details