Container queries: Why can't I style the container selector in the container query

5.9k Views Asked by At

When using container queries. I can't style the element that the container query is set on in the container query itself. Like below.

.container {
  width: 250px;
  height: 250px;
  background-color: hotpink;
  container-type: inline-size;
}

@container (max-width: 768px) {
  /* This selector doesn't work here */
  .container {
    background-color: red;
  }
}
<div class="container"></div>

Does anyone know why this can't be done?

1

There are 1 best solutions below

3
On BEST ANSWER

I think the main issue is:

  • the @container targets things inside the container element so you cannot target the container itself

Below is the container with a test div that swaps background colour using the container query.

If you put the width back onto the container, then it will only show one background and therefore the need for the query is lost as the container can't change size.

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

.test {
  width: 250px;
  height: 250px;
  background-color: hotpink;
}

@container (max-width: 768px) {
  .test {
    background-color: red;
  }
}
<div class="container">
  <div class="test"></div>
</div>