Encodera

Thanks for reading!

Donate to the site — we work hard for you.

HTML & CSS reference

contain

Promises the browser that an element is independent of the rest of the page, so changes inside it do not force the whole page to be recalculated.

Syntax

contain: layout paint;

Values

ParameterTypeDescription
layoutkeywordThe layout inside does not affect anything outside.
paintkeywordNothing inside is painted outside the element's box (it is clipped like `overflow: hidden`).
size, inline-sizekeywordThe element's size does not depend on its content (`inline-size` — only the width).
stylekeywordCounters inside do not affect counters outside.
content, strictkeywordShorthands: `content` = layout + paint + style, `strict` = the same plus size.

Examples

A widget with contain: paint clips the badge that sticks out:

<style>
  .widget {
    contain: paint;
    width: 200px; padding: 12px; border: 1px solid #ccc; position: relative;
  }
  .badge { position: absolute; top: -10px; right: -10px; background: crimson; color: white; padding: 2px 8px; }
</style>
 
<div class="widget">
  Chat widget
  <span class="badge">New</span>
</div>

Notes

contain is an optimization hint with visible side effects: paint clips, size makes an empty element collapse to 0 unless you give it a size. Container queries set contain: inline-size for you through container-type. Usually content-visibility: auto gives the benefit with less risk. Supported in all current browsers.

See also

  • content-visibility — Lets the browser skip laying out and painting an element's content while it is off screen — a cheap speed-up for long pages.
  • @container — Applies rules depending on the size of a container rather than the window.
  • overflow — What to do with content that does not fit into the element.
  • will-change — Warns the browser that a property is about to change, so it can prepare in advance.

In the tutorial

  • Page speed — Fast loading basics for HTML and CSS — render-blocking CSS and critical styles, preload and preconnect, image sizes, loading=lazy and fetchpriority, content-visibility and contain, layout shifts and checking in Lighthouse.

Thanks for reading!

Donate to the site — we work hard for you.