CSS Container Style Queries: Data-Driven Component Variants

CSS Container Style Queries let you apply styles based on the computed values of custom properties on a container element — not just its size. This enables truly data-driven styling: change a single custom property in PHP or JavaScript and entire component variants update automatically.

Problem: A CSS component needs different visual variants based on its own data — a card that is "featured" renders differently — but CSS class-based variants require JavaScript to read data attributes and toggle classes.

Solution: Use CSS Container Style Queries (@container style()) to apply styles based on a custom property value set on the container. Define --featured: 1 as inline style in PHP/HTML, then write @container style(--featured: 1) { … } in CSS — no JavaScript needed to branch on component state.

The examples below define a container with a --theme custom property, use a style query to switch a card's color scheme, and apply this pattern in a WordPress block theme to handle light/dark mode per block.

/* 1. Declare the element as a style-queryable container */
.wp-block-group {
    container-type: style;   /* enables style queries */
    container-name: card;
}

/* 2. Style query — fires when --variant equals 'dark' */
@container card style(--variant: dark) {
    .wp-block-group {
        background: #1a1a2e;
        color: #e0e0e0;
    }
    a { color: #7eb8f7; }
}

@container card style(--variant: highlight) {
    .wp-block-group {
        background: #fff3cd;
        border-left: 4px solid #ffc107;
    }
}

/* 3. Set the custom property via a utility class or inline style */
.card--dark      { --variant: dark; }
.card--highlight { --variant: highlight; }

Use style queries in a WordPress block theme to toggle a section's appearance from the editor:

/* theme.json sets a custom property via spacing/color presets.
   The block editor outputs an inline style like:
   style="--wp--custom--section-style: hero"
   Use a style query to react to it: */

.wp-block-cover {
    container-type: style;
    container-name: cover-section;
}

@container cover-section style(--wp--custom--section-style: hero) {
    .wp-block-cover__inner-container h1 {
        font-size: clamp(2.5rem, 6vw, 5rem);
        text-shadow: 0 2px 8px rgb(0 0 0 / .4);
    }
}

@container cover-section style(--wp--custom--section-style: minimal) {
    .wp-block-cover {
        min-height: 30vh;
    }
    .wp-block-cover__inner-container {
        text-align: left;
        max-width: 640px;
    }
}

NOTE: Container Style Queries are supported in Chrome 111+, Safari 18+, and Firefox 128+. For older browsers, provide fallback styles outside the query block — the component will still render, just without the variant-specific styling.

Leave Comment

Your email address will not be published. Required fields are marked *