All resources
CSS & TailwindBeginner2 min read

Modern CSS Layout Cheatsheet

Flexbox, Grid, fluid sizing and container queries: the handful of patterns that solve most real-world layouts.

Flexbox or Grid?

Use Flexbox when content decides the size of items along one axis (toolbars, nav bars, button groups). Use Grid when the layout decides the size of items in two dimensions (cards, dashboards, page shells).

NeedReach forKey properties
Items in a row that wrapFlexboxflex-wrap: wrap, gap
Push one item to the endFlexboxmargin-left: auto
Equal columns that reflowGridrepeat(auto-fit, minmax())
Header / sidebar / main shellGridgrid-template-areas
Overlap elementsGridSame grid-area on both

Responsive grids without media queries

auto-fit with minmax() creates as many columns as fit, each at least the minimum width. Wrapping the minimum in min() keeps a single column from overflowing on narrow screens.

cards.cssCSS
.cards {  display: grid;  gap: 1.5rem;  grid-template-columns: repeat(auto-fit, minmax(min(18rem, 100%), 1fr));}

Centering, the reliable way

CSS
/* Both axes, any content */.center {  display: grid;  place-items: center;}/* Constrained, centered page content */.container {  width: min(72rem, 100% - 2rem);  margin-inline: auto;}

Fluid type and spacing with clamp()

clamp(min, preferred, max) scales a value with the viewport while respecting limits. Mixing rem into the preferred value keeps text zoomable for accessibility.

CSS
h1 {  font-size: clamp(2rem, 1.2rem + 3vw, 4rem);}.section {  padding-block: clamp(3rem, 8vw, 7rem);}

Container queries for reusable components

Media queries react to the viewport; container queries react to the space a component actually has. That makes the same card work in a sidebar and in the main column.

CSS
.card-wrapper {  container-type: inline-size;}@container (min-width: 32rem) {  .card {    display: grid;    grid-template-columns: 12rem 1fr;  }}