contain
contain isolates (contains) a box from the rest of the page, promising the browser that changes inside it do not affect anything outside. The browser can then redo work for just that part, which makes rendering faster.
Syntax
none | strict | content | [ [ size | inline-size ] || layout || style || paint ]Preview
Code
.box {
overflow: visible;
height: auto;
contain: paint;
}Controls
About
Values
none: no containment. This is the initial value.size: the box is sized as if it had no contents. A box without a set height shrinks even though it has contents.inline-size: the same assize, but only along the line direction (the width in horizontal writing). It cannot be combined with size.layout: isolates the layout inside. Floats and margins inside no longer reach outside, andposition: absoluteandposition: fixedelements inside are placed relative to this box.style: keeps counters such ascounter-incrementand quote nesting from affecting anything outside the box.paint: clips the contents at the outer edge of the padding (the overflow clip edge). As withoverflow: clip, anything that overflows is no longer visible.strict: the same assize layout style paint.content: the same aslayout style paint, so everything but size.
Reading the preview
The preview on this page uses helper declarations, overflow: visible and height: auto, so that overflowing contents stay visible and the box height follows its contents. The long URL on the first line sticks out on the right. With paint, the URL is clipped. With size, the box shrinks and the text hangs out below it. With strict, both happen and almost nothing of the shrunken box's contents is visible.
inline-size changes nothing in this preview, because the box width is set to 240px. On a box whose width comes from its contents (such as display: inline-block or a float), the width shrinks as if it had no contents.
When to use it
- Put
contain: contenton self-contained widgets or on each item of a long list, so that a change inside only makes the browser redo that part. container-typefor container queries usessizeorinline-sizecontainment internally, so that the container width does not depend on contents that in turn ask for that width.
Watch out
layoutandpaintalso create a stacking context. z-index values inside no longer compete with elements outside the box.- A
layoutbox is treated as having no baseline, so its position changes when it is aligned to the baseline in a line. sizeandpaintdo not apply to table rows or todisplay: inlineelements.sizedoes not apply to table cells or to the table itself either, butpaintdoes apply to cells.- Works in all major browsers.
stylearrived in Firefox 103 and Safari 27.