csscontainer-queries

How to modify CSS property of element with container-type: inline-size by @container query


I'm looking for solution how to modify property in css of element with container-type: inline-size; (not in children) by @container query.

Consider HTML

<div class="card card--1">
  <h2 class="card__title">
    card 1 title
  </h2>
  <p class="card__body">
    lorem ipsum
  </p>
</div>
<div class="card card--2">
  <h2 class="card__title">
    card 2 title
  </h2>
  <p class="card__body">
    lorem ipsum
  </p>
</div>

and CSS

.card {
  container-type: inline-size;
  background-color: antiquewhite;
}
.card--1 {
  width: 200px;
}
.card--2 {
  width: 300px;
}

@container (min-width: 250px) {
  .card {
    /* do not work */
    background-color: aqua;
  }
  .card__title {
    /* works fine */
    color: red;
  }
}

How to modify above example to change background-color in .card without changing HTML markup? Working example in codesandbox.


Solution

  • Container queries are still an experimental features, not yet widely implemented.

    With container queries you cannot change the styles of the container element itself. You can only change the styles of the children.

    With css container queries we can define an element as a container. We will use that container in a sort of "media query". So you can then only style the element inside the "media query".

    I wish it would be possible to style the container itself. this would be great for instance for webcomponents.

    It is still possible to achieve what you want, but you need to add some extra markup. You need to add an extra "wrapper" inside you container.

    So around your element, which already has your styles, add a new div (for instance <div class="card-container">, which will really only work as a container for your card. You can then in your css make that wrapper div your container and then style your card accordingly.

    something like:

    <div class="card-container">
      <div class="card card--1">
        <h2 class="card__title">
          card 1 title
        </h2>
        <p class="card__body">
          lorem ipsum
        </p>
      </div>
    </div>
    

    and in your css:

    .card-container {
      container-type: inline-size;
    }
    
    @container (min-width: 250px) {
      .card {
        ...
      }
    }
    

    You can see how the browser support is here: https://caniuse.com/css-container-queries

    There is some good information about it here: