CSS Flexbox

Learn how to use the Flexible Box Layout system for building responsive layouts.

What is Flexbox?

Flexbox (Flexible Box Module) is a one-dimensional layout method designed for laying out items in rows or columns. Items in a flex container can "flex" their sizes to either grow to fill unused space or shrink to avoid overflow.

Flexbox makes it easier to design flexible responsive layouts without using float or positioning. It's particularly good at:

Flex Container Basics

To start using flexbox, you need to first define a container as a flex container:

.container {
  display: flex;
}

Here's a simple example of a flex container with three items:

Item 1
Item 2
Item 3

Flex Direction

The flex-direction property defines the direction in which flex items are placed:

flex-direction: row | row-reverse | column | column-reverse;

Row (Default)

Item 1
Item 2
Item 3

Row Reverse

Item 1
Item 2
Item 3

Column

Item 1
Item 2
Item 3

Column Reverse

Item 1
Item 2
Item 3

Flex Wrap

The flex-wrap property controls whether items are forced into a single line or can be wrapped onto multiple lines:

flex-wrap: nowrap | wrap | wrap-reverse;

No Wrap (Default)

Item 1
Item 2
Item 3
Item 4
Item 5

Wrap

Item 1
Item 2
Item 3
Item 4
Item 5

Wrap Reverse

Item 1
Item 2
Item 3
Item 4
Item 5

Justify Content

The justify-content property aligns items along the main axis (horizontally for row, vertically for column):

justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly;

Flex Start (Default)

1
2
3

Flex End

1
2
3

Center

1
2
3

Space Between

1
2
3

Space Around

1
2
3

Space Evenly

1
2
3

Align Items

The align-items property aligns items along the cross axis (vertically for row, horizontally for column):

align-items: stretch | flex-start | flex-end | center | baseline;

Stretch (Default)

1
2
3

Flex Start

1
2
3

Flex End

1
2
3

Center

1
2
3

Baseline

Aligns items so that their baselines align:

Small
Medium
Regular
Large

Flex Item Properties

Flex items can also have their own properties:

flex-grow: number; /* default 0 */
flex-shrink: number; /* default 1 */
flex-basis: length | auto; /* default auto */
flex: [grow] [shrink] [basis]; /* shorthand */

Flex Grow

Determines how much the flex item will grow relative to other flex items:

Grow: 1
Grow: 2
Grow: 3

Flex Basis

Sets the initial main size of a flex item:

Basis: 100px
Basis: 100px
Auto

Responsive Flexbox Example

Here's an example of a responsive layout that adapts to different screen sizes using flexbox:

Card 1
Card 2
Card 3
Card 4

Resize your browser window to see how the items adjust and wrap.

.responsive-flex {
  display: flex;
  flex-wrap: wrap;
}

.responsive-item {
  flex: 1 1 300px; /* grow shrink basis */
}

Best Practices