🌞

Flexbox

The flexible box layout - your go-to tool for one-dimensional layouts

Flexbox Fundamentals

Flexbox makes it easy to align and distribute space among items in a container, even when their size is unknown or dynamic.

Flex Direction

1
2
3

Row (default)

1
2
3

Column

/* Flex container */
.container {
    display: flex;
    flex-direction: row; /* default */
}

/* Other directions */
.column { flex-direction: column; }
.row-reverse { flex-direction: row-reverse; }
.column-reverse { flex-direction: column-reverse; }

Flex Wrap

Item 1
Item 2
Item 3
Item 4
Item 5

Flex-wrap: wrap

/* Allow items to wrap */
.container {
    display: flex;
    flex-wrap: wrap;
}

/* Shorthand */
.container {
    display: flex;
    flex-flow: row wrap;
}

Flex Grow, Shrink & Basis

No grow
Grow: 1
Grow: 2
/* Flex item properties */
.item {
    flex-grow: 0;    /* Don't grow */
    flex-shrink: 1;  /* Can shrink */
    flex-basis: auto; /* Base size */
}

/* Shorthand */
.item {
    flex: 1; /* grow: 1, shrink: 1, basis: 0 */
}

/* Common patterns */
.item { flex: 1 1 auto; } /* Flexible */
.item { flex: 0 0 200px; } /* Fixed width */

Gap Property

1
2
3
4

Gap: 1rem

/* Modern gap property */
.container {
    display: flex;
    gap: 1rem; /* All directions */
}

/* Separate row and column gaps */
.container {
    row-gap: 1rem;
    column-gap: 2rem;
    /* or */
    gap: 1rem 2rem;
}

Alignment & Justification

Flexbox shines when it comes to alignment. Control both main axis and cross axis alignment with ease.

Justify Content (Main Axis)

1
2
3

flex-start

1
2
3

center

1
2
3

flex-end

1
2
3

space-between

1
2
3

space-around

1
2
3

space-evenly

/* Main axis alignment */
.container {
    display: flex;
    justify-content: flex-start; /* default */
    justify-content: center;
    justify-content: flex-end;
    justify-content: space-between;
    justify-content: space-around;
    justify-content: space-evenly;
}

Align Items (Cross Axis)

1
2
3

flex-start

1
2
3

center

1
2
3

flex-end

1
2
3

stretch

1
2
3

baseline

/* Cross axis alignment */
.container {
    display: flex;
    align-items: stretch; /* default */
    align-items: flex-start;
    align-items: center;
    align-items: flex-end;
    align-items: baseline;
}

/* Individual item alignment */
.item {
    align-self: auto; /* default */
    align-self: center;
}

Perfect Centering

Perfectly Centered!
/* The holy grail of centering */
.container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 200px;
}

/* Even simpler with place-content */
.container {
    display: flex;
    place-content: center;
}

Interactive Flexbox Playground

Experiment with different flexbox properties and see the results in real-time!

Container Properties

10px

Item Properties

5
0
1
1
2
3
4
5
.container {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: flex-start;
    align-items: stretch;
    gap: 10px;
}