Container Queries: Beyond the Viewport
Media queries are great, but they have a limitation: they only respond to the size of the entire viewport (the browser window). This means a component has no idea how much space it has been given within a layout.
Container queries solve this. They allow a component to change its styles based on the dimensions of its direct parent container. This makes components truly modular and reusable.
How it works:
- You define an element as a "query container" using the container-type property.
- You use the @container at-rule (which works just like @media) to apply styles to its children when the container reaches a certain size.
Code Snippet: A Responsive Card Component
Imagine a card component that can be placed in a wide main content area or a narrow sidebar. We want it to stack vertically in the narrow space and sit side-by-side in the wide space.
HTML:
HTML
<div class="sidebar"> <div class="card">...</div> </div> <div class="main-content"> <div class="card">...</div> </div>
CSS:
CSS
/* 1. Define the containers. Any .sidebar or .main-content can now be queried. */
.sidebar, .main-content {
  container-type: inline-size;
}
/* Default card styles (for narrow containers) */
.card {
  display: flex;
  flex-direction: column;
}
/* 2. Apply new styles when the card's container is wider than 400px */
@container (min-width: 400px) {
  .card {
    flex-direction: row;
    align-items: center;
  }
}
Now, the same .card component will look different depending on where it's placed, without any media queries!
CSS Subgrid: Perfecting Nested Layouts
CSS Grid is amazing for top-level page layouts. But when you nest a grid inside another grid, the inner grid's tracks have no relationship to the parent grid's tracks. This can make alignment difficult.
Subgrid solves this. By setting grid-template-columns or grid-template-rows to subgrid on a nested grid item, you tell it to adopt the track sizing of its parent grid.
Code Snippet: Aligning Nested Items
HTML:
HTML
<div class="parent-grid">
  <div class="item subgrid-item">
    <div>Item A</div>
    <div>Item B</div>
  </div>
  <div class="item">Regular Item</div>
</div>
CSS:
CSS
.parent-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}
.subgrid-item {
  /* This item spans 3 columns of the parent grid */
  grid-column: 1 / 4;
  
  /* Make its own grid a subgrid */
  display: grid;
  grid-template-columns: subgrid; /* This is the magic! */
  gap: 5px;
}
/* Now, the children of .subgrid-item will align perfectly
   with the columns of .parent-grid */
.subgrid-item > div {
  grid-column: span 1; /* Each takes up one track from the parent */
}