Search code examples
csscss-variablescontainer-queries

How to Redefine CSS Custom Property Value for :Root Within Container Query Body?


I'm trying to set a CSS custom property within the :root and then change the value depending on the container's size using a container query, but it's not working. Here's an example:

<div class="my-container">
  <div class="test">
    Testing
  </div>
</div>

With these styles:

:root {
  --bg-color: red;
}

@container (min-width: 500px) {
  :root {
    --bg-color: green; /* This doesn't seem to do anything. */
  }
  .test {
    border: 5px solid black;
  }
}

.my-container {
  container-type: inline-size;
}

.test {
  background-color: var(--bg-color);
}

On a larger screen (500px or wider), I would expect the .test element with have a green background color, but instead it is red.

The black border is there just to confirm the container query is doing something at all.

In other words, I would expect this:

Green Background

But I actually get this instead:

Red Background

I'm using Chrome 120 (also tried latest Firefox). I tried a number of variations that didn't seem to change the outcome (e.g., invert container/root hierarchy, use html instead of :root, use a named container, and so on). I think using .test instead of :root for the selector within the container query body did actually work, but that's not what I'm trying to accomplish as my use case is to make something reusable.

Any idea why I can't get this background color to change to green on a larger screen via this altered CSS custom property value within a container query body?


Solution

  • Because :root is not a descendant of .my-container, so @container (...) { :root {...} matches nothing.

    In fact, since :root cannot be a descendant of another element, and selectors in container queries are always scoped to the container it can never match inside a container query.

    So you have to redefine the --bg-color to an element inside the container if your rule is inside that @container.