CodeBlanks Logo Icon CodeBlanks

Container style

CSS course · Expert · Lesson 22/53

Learn container styles with the style() function.

The style() function

Size queries check the container's width or height. The style() function queries a computed custom property on the container. So the same container can switch styles based on its own properties.

The syntax: @container style(--theme: dark). The inner styles apply when the container's --theme property is dark. You swap appearance through a custom property value, not a class change.

This is an elegant way to bind a component's look directly to data.

Custom property queries

The power of style() is that a component's state can ride on a custom property. Set --theme: dark on an ancestor and the descendant automatically goes dark; no need to toggle a class with JavaScript.

Multiple conditions can combine: @container style(--theme: dark) and (min-width: 320px). Both theme and size are checked in one query; the component adapts to both.

Exercise Switch theme with style()

Give the .card selector container-type: inline-size and set the custom property --theme: light. Then, inside an @container style(--theme: dark) query, set background: #1f2937 on the .card-body sub-selector. The card shows a dark background in dark theme.

Show example solution
/* open the card container, default theme light */
/* darken background in dark theme */
.card {
  container-type: inline-size;
  --theme: light;
}
@container style(--theme: dark) {
  .card-body {
    background: #1f2937;
  }
}

Test yourself

  1. Which is a valid style() query?

    • @container (style: --theme)
    • @container style(--theme)
    • @container (--theme: dark)
    • @container style(--theme: dark)
    Show answer

    @container style(--theme: dark) — Correct. The style() function takes a custom property name and value.

  2. Write the style() condition

    @container ____(--theme: dark) {
      .card { color: white; }
    }
    Show answer
    @container style(--theme: dark) {
      .card { color: white; }
    }
  3. Match query types

    style()
    Style query
    @container style(...)
    Style condition
    --theme: dark
    Custom property value
    @container (min-width: ...)
    Size condition

All lessons in Expert