CSS Flexbox

What Is Flexbox?

Flexbox (Flexible Box Layout) is a one-dimensional layout model that helps align and distribute space among items in a container. It works well for horizontal or vertical alignment.

.container {
  display: flex;
}
Box 1
Box 2
Box 3

Main Axis and Cross Axis

Flex items are laid out along the main axis (by default: horizontal), while the cross axis runs perpendicular.

.container {
  flex-direction: row;
}

.container-column {
  flex-direction: column;
}

Justify Content

Use justify-content to align items on the main axis:

  • flex-start
  • center
  • flex-end
  • space-between
  • space-around
  • space-evenly

Visual examples of each:

flex-start:
Box A
Box B
center:
Box A
Box B
flex-end:
Box A
Box B
space-between:
Box A
Box B
space-around:
Box A
Box B
space-evenly:
Box A
Box B

Align Items

Use align-items to align flex items on the cross axis:

  • stretch (default)
  • flex-start
  • flex-end
  • center
  • baseline
stretch (default):
Box A
Box B
flex-start:
Box A
Box B
flex-end:
Box A
Box B
center:
Box A
Box B
baseline:
Text A
Text B

Flex Item Properties

You can control the behavior of individual items using:

  • flex-grow: ability to grow
  • flex-shrink: ability to shrink
  • flex-basis: initial size
  • flex: shorthand for grow, shrink, basis
  • align-self: override cross-axis alignment
.item {
  flex: 1;
  align-self: center;
}

Practice Prompt

Create a flex container with three evenly spaced items:

<div style={{
  display: "flex",
  justifyContent: "space-evenly",
  alignItems: "center",
  height: "100px",
  backgroundColor: "#f0f0f0"
}}>
  <div style={{ backgroundColor: "#ff9999", padding: "10px" }}>Item 1</div>
  <div style={{ backgroundColor: "#99ccff", padding: "10px" }}>Item 2</div>
  <div style={{ backgroundColor: "#99ff99", padding: "10px" }}>Item 3</div>
</div>

You can copy and paste this code in your IDE to run!

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic