Lab 10: CSS Performance Deep

Time: 30 minutes | Level: Advanced | Docker: docker run -it --rm node:20-alpine sh

Overview

Master CSS performance engineering: contain, content-visibility, @layer for cascade management, selector performance, will-change budgeting, and CSS logical properties.


Step 1: CSS Contain

contain isolates an element from the rest of the page, enabling browser optimizations:

/* Individual contain values */
.widget {
  contain: layout;  /* layout changes don't affect outside */
  contain: paint;   /* painting is clipped to the element's bounds */
  contain: size;    /* element's size doesn't depend on its children */
  contain: style;   /* counters and quotes don't escape this element */
}

/* Shorthand values */
.card {
  contain: content; /* = layout + paint (most useful combo) */
}

.fixed-size-widget {
  contain: strict;  /* = layout + paint + size (most aggressive) */
  width: 300px;
  height: 200px; /* must set explicit size with 'strict' */
}

/* inline-size containment (for container queries) */
.container {
  container-type: inline-size; /* auto-applies contain: inline-size layout style */
}

/* When to use contain */
.sidebar-widget { contain: content; }
/* — Each widget's reflows won't ripple to the page */

.ad-unit { contain: strict; }
/* — Ads can't affect page layout */

.code-editor { contain: layout paint; }
/* — Complex inner renders won't cause page reflow */

💡 contain: content is the most practical value. It isolates layout and paint without requiring a fixed size.


Step 2: content-visibility


Step 3: @layer for Cascade Management


Step 4: Selector Performance


Step 5: will-change Budget


Step 6: CSS Logical Properties


Step 7: CSS Layer Import Strategy


Step 8: Capstone — Contain Property Analyzer

(Create the file:)

📸 Verified Output:


Summary

Feature
Value
Performance Impact

contain: content

layout + paint

Isolate component reflows

contain: strict

layout+paint+size

Maximum isolation

content-visibility: auto

Skip off-screen rendering

contain-intrinsic-size

auto 500px

Prevent scroll jump

@layer

Layer order

Zero-specificity cascade control

Avoid * selector

Reduce selector matching

will-change: transform

GPU layer promotion

Logical properties

margin-inline

i18n + performance

Class selectors

.class {}

Fastest selector type

Avoid !important

Use @layer instead

Last updated