CodeOath
← All posts
HTML & CSS70 min total · 18 parts

CSS Fundamentals: The Box Model, Specificity, Positioning, and Layout

Contents — Part 15 of 18: Responsive Design: Media Queries and Container Queries
Part 15 of 18 · ~1 min

Responsive Design: Media Queries and Container Queries

A media query applies styles conditionally based on the viewport (or device) itself:

.layout {
  display: grid;
  grid-template-columns: 1fr;
}

@media (min-width: 768px) {
  .layout {
    grid-template-columns: 250px 1fr;
  }
}

min-width breakpoints (mobile-first: start with the small-screen styles, add rules that apply above a width) are the conventional approach over max-width breakpoints, since they compose more predictably as more breakpoints are added.

A container query is the more recent alternative — it responds to the size of an element's containing element, not the viewport, which matters for a component (like a card) that might render inside a wide main column in one place and a narrow sidebar in another:

.card-container {
  container-type: inline-size; /* opt this element in as a query container */
}

@container (min-width: 400px) {
  .card { display: flex; } /* only applies when the CONTAINER is at least 400px, not the viewport */
}

Media queries answer "how big is the screen?" — container queries answer "how much space does this component actually have?", which is usually the more correct question for a reusable component that doesn't control its own placement.