ShareYourGroupShareYourGroupCSS Lab

CSS flexbox guide: the properties you need and nothing more

Flexbox solves one problem well: lay out items in a row or a column and share the space.

Container and items

Add display: flex to a parent and its direct children become flex items. Everything else is a property of the container or of an item. Only direct children are affected; grandchildren need their own flex container.

Container properties

Item properties

Recipes

A navigation bar: display: flex; justify-content: space-between; align-items: center; puts the logo at one end and the links at the other. A row of cards that wrap: display: flex; flex-wrap: wrap; gap: 16px; with flex: 1 1 240px on each card. A footer pushed to the bottom: make the page container display: flex; flex-direction: column; min-height: 100vh; and give the main content flex: 1.

Mistakes people make

  1. Text overflow: a flex item will not shrink below its content width unless you set min-width: 0. This is why a long word or URL stretches a flex layout past the screen.
  2. Images stretching. Items are stretched on the cross axis by default; set align-items: flex-start or give the image align-self.
  3. Using margins and gap together and getting double spaces.
Is flexbox or grid better for page layout?

Both. Flexbox for components in one line, grid for areas with rows and columns. See the comparison page.

This is an independent site. It is not connected with the W3C, MDN, Google, Apple, Mozilla or Microsoft. Browser and product names belong to their owners.