Read more

CSS: CSS Container Queries

Emanuel
March 16, 2023Software engineer at makandra GmbH

Container queries enable you to apply styles to an element based on the size of the element's container. If, for example, a container has less space available in the surrounding context, you can hide certain elements or use smaller fonts. Container queries are an alternative to media queries, which apply styles to elements based on viewport size or other device characteristics.

This feature is now stable across browsers.

Warning

This feature landed in browsers in the beginning of 2023. According to our support policy this will become generally usable starting April 2025.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

Below is the example from the linked MDN web docs:

<div class="post">
  <div class="card">
    <h2>Card title</h2>
    <p>Card content</p>
  </div>
</div>
.post {
  container-type: inline-size;
}

/* Default heading styles for the card title */
.card h2 {
  font-size: 1em;
}

/* If the container is larger than 700px */
@container (min-width: 700px) {
  .card h2 {
    font-size: 2em;
  }
}

Further reading:

This article Show archive.org snapshot has plenty more examples and use cases.

Posted by Emanuel to makandra dev (2023-03-16 09:21)