Asia/Dhaka
Posts

Demystifying CSS Container Queries

October 22, 2024
For over a decade, responsive web design has relied almost entirely on CSS Media Queries. They allow developers to change the styling of elements based on the width of the viewport (the browser window).
Css
/* Media Query Example */
.card {
  display: flex;
  flex-direction: column;
}

@media (min-width: 768px) {
  .card {
    flex-direction: row;
  }
}
This works perfectly for page-level layouts. However, in the era of component-based architectures (React, Vue, Web Components), Media Queries fall short. A component like a <Card /> might be placed in a wide main content area, or it might be squeezed into a narrow sidebar. If the viewport is 1000px wide, the Media Query triggers the flex-direction: row layout regardless of where the card is placed. This results in the card breaking if it's placed in a narrow 300px sidebar while on a large screen. Container Queries solve this fundamental problem. Instead of querying the viewport width, they allow an element to query the width of its parent container. This means a component can finally be truly self-contained and modular. It responds to the space it is given, not the space of the entire browser window. Using Container Queries is surprisingly simple. It involves two steps: 1. Define a Container Context First, you must define the parent element as a "container". You do this using the container-type property.
Css
.sidebar {
  container-type: inline-size;
  /* You can optionally name the container */
  container-name: sidebar-container; 
}

.main-content {
  container-type: inline-size;
  container-name: main-container;
}
Setting inline-size tells the browser to track the width of this container. 2. Query the Container Next, you use the @container rule to apply styles based on the container's width.
Css
.card {
  display: flex;
  flex-direction: column;
}

/* This applies when the PARENT container is at least 400px wide */
@container (min-width: 400px) {
  .card {
    flex-direction: row;
  }
}
With this setup, you can take the exact same <Card /> component and place it anywhere:
  1. If placed in .main-content (which might be 800px wide), the container query triggers, and the card displays as a row.
  2. If placed in .sidebar (which might be 300px wide), the container query does not trigger, and the card gracefully falls back to a column layout.
As of late 2023, Container Queries have excellent support across all major modern browsers (Chrome, Safari, Firefox, Edge). They are no longer an experimental feature; they are ready for production. Container Queries represent a paradigm shift in UI development. By moving away from viewport-centric design to component-centric design, we can finally build truly reusable, resilient UI components.
On this page
Hey! Got questions?Ask me anything 👋