HTML & CSS Foundations · 18 min · 130 XP

Responsive layouts

Make a layout that holds together from a phone to a widescreen monitor, mostly without media queries.

Responsive design is less about breakpoints than about letting elements decide their own size. Before adding a single media query, get rid of what fights the screen: fixed widths, images wider than their container, and rows that can't wrap. A lot of layouts then work at every width on their own.

Intrinsic layout: it wraps when it has to
.cards {
  display: flex;
  flex-wrap: wrap;          /* move to a new line instead of squashing */
  gap: 1rem;
}
.card {
  flex: 1 1 15rem;          /* grow, shrink, and aim for 15rem before wrapping */
}
img {
  max-width: 100%;          /* never wider than its container */
  height: auto;             /* keep the proportions */
}

flex: 1 tells an item to take a share of whatever space is left after its siblings have what they need. Adding a basis, as in flex: 1 1 15rem, says about 15rem, but grow into spare space. Three cards sit in a row on a laptop and stack on a phone, with no media query. Watch for one catch: a flex item won't shrink below its content's width unless you give it min-width: 0, which is why long URLs sometimes burst out of cards.

Loading your workspace…