GAZAR

Principal Engineer | Mentor

Reviewing CSS Container Queries

Reviewing CSS Container Queries

Container Queries provide a mechanism for defining styles based on the dimensions of individual container elements, rather than the overall viewport. This allows for more granular control over responsive behaviour, enabling elements to adapt intelligently to changes in their containing context.

@container (min-width: 30rem) {
  /* Styles applied when the container width is at least 30rem */
}
@container (min-width: 30rem) {
  h1 {
    font-size: 2rem;
  }
}

@container (min-width: 60rem) {
  h1 {
    font-size: 3rem;
  }
}

So the different here is if h1! is in a div element and that contanier is less than 60 rem or 30rem, h1 size would be different and this is not just depend on the page width.

You can also name something

.post {
  container-type: inline-size;
  container-name: sidebar;
}

And then style based on the size of that element

@container sidebar (min-width: 700px) {
  .card {
    font-size: 2em;
  }
}

I have not seen a lot of usecases of @containers that developers prefer to use this over media queries, since it might be a bit complicated to imagine the container size.

However, this is a feature that it's worth learning and I am sure it has it's own usecases.

Benefits of Container Queries

  • Granular Control: Fine-tune responsive behavior on a per-element basis.
  • Modular Design: Encourage component-based layouts that adapt seamlessly to their containers.
  • Simplified Maintenance: Reduce complexity by targeting specific elements rather than relying solely on viewport dimensions.

CSS @Container Queries represent a significant leap forward in the realm of responsive web design, offering unparalleled flexibility and precision. By embracing Container Queries, developers can create layouts and typography that fluidly respond to the size of their container elements, resulting in more intuitive and user-friendly experiences. With the power of TypeScript, integrating Container Queries into your workflow is easier than ever. Embrace this transformative feature and unlock new possibilities for responsive design excellence.