CS CSS

CSS: Flexbox Layout

What you will learn

Flexbox is a one-dimensional layout method for arranging items in rows or columns. It excels at distributing space and aligning items.

Enabling flexbox

.container {
    display: flex;           /* enable flexbox */
    justify-content: center; /* horizontal alignment */
    align-items: center;     /* vertical alignment */
    gap: 10px;               /* space between items */
    flex-wrap: wrap;         /* allow items to wrap onto next line */
}

Key flexbox properties

On the container (parent)

Property What it does Common values
display: flex Enables flexbox flex, inline-flex
flex-direction Direction of items row (default), column, row-reverse
justify-content Alignment along main axis center, space-between, space-around, flex-start
align-items Alignment along cross axis center, stretch, flex-start, flex-end
flex-wrap Allow wrapping nowrap, wrap, wrap-reverse
gap Spacing between items 10px, 1rem

On the items (children)

Property What it does
flex-grow How much to grow if space is available (0 = don't grow)
flex-shrink How much to shrink if space is tight
flex-basis Starting size before growing/shrinking
align-self Override align-items for this item
.item { flex: 1; }         /* shorthand: grow=1, shrink=1, basis=0 — equal width */
.item { flex: 0 0 200px; } /* fixed 200px, no grow, no shrink */

When to use flexbox

  • Centering content horizontally and vertically (justify-content: center; align-items: center)
  • Navigation bars with evenly spaced links
  • Card layouts that wrap
  • Any one-dimensional row or column arrangement

Common mistakes

  • Setting justify-content on a single item instead of the container.
  • Forgetting flex-wrap: wrap and having items overflow or shrink unexpectedly.
  • Using display: inline-flex when you meant display: flex.
  • Applying flex properties to containers inside a flex item instead of the flex item itself.

Quick check below!