Sub topic 2
Size containment and content-visibility
Assume you know CSS selectors, the box model, positioning, overflow, and basic DevTools. This chapter focuses on how containment changes sizing and rendering.
Size containment
Size containment makes an element’s size independent of its contents. When the browser calculates the element’s size, it treats the contents as if they contribute no size. Give the element an explicit size, or it may collapse:
.badge {
contain: size;
width: 120px;
height: 40px;
}Style containment isolates style-dependent effects such as counters and quotation marks. It does not isolate normal inheritance, so inherited properties can still reach descendants.
The strict and content shorthands
The contain property accepts several values:
| Value | Main guarantee |
|---|---|
| `size` | Contents do not determine the element’s size |
| `content` | `layout`, `paint`, and `style` containment |
| `strict` | `size`, `layout`, `paint`, and `style` containment |
Use content for an independent component whose size still depends on its contents. Use strict only when you can provide a stable size.
Side effects of containment
Containment changes more than performance. Layout containment creates an independent formatting context and a containing block for positioned descendants. A positioned child may therefore use its contained ancestor instead of an outer ancestor.
Paint containment clips descendants to the element’s padding box and creates a stacking context. Shadows, menus, or tooltips that extend outside the box can disappear. Test overflow before adding paint containment.
content-visibility and intrinsic size
content-visibility: auto combines containment with skipped rendering. The browser can avoid rendering an off-screen section until it approaches the viewport:
.feed-item {
content-visibility: auto;
contain-intrinsic-size: auto 600px;
}contain-intrinsic-size supplies a placeholder size while the contents are skipped. This prevents the page from treating the section as zero-height and reduces scrollbar jumps. With the auto keyword, the browser can remember the actual rendered size and reuse it later.
content-visibility: hidden also skips rendering but keeps the element’s state, making it useful for cached panels or inactive views. Choose auto for viewport-based optimization and hidden when your interface deliberately controls visibility.
Exercise
Why should a size-contained element usually have an explicit width or height?
Show answer
Its contents no longer contribute to its size, so an auto-sized dimension can become zero or otherwise be too small.