Lesson 7 of 18

CSS Flexbox ⬇

🎯 Grades 9–12 ⏱ ~35 minutes 💚 Intermediate

What You'll Learn

  • Use display: flex to create layouts
  • Understand justify-content and align-items
  • Build a responsive navigation bar

What Is Flexbox?

Flexbox is a CSS layout mode that makes it easy to arrange elements in a row or column and control spacing, alignment, and sizing. Before Flexbox, centering things in CSS was surprisingly difficult!

CSS
.container {
  display: flex;            /* activate flexbox */
  flex-direction: row;      /* row (default) or column */
  justify-content: center;  /* align along main axis */
  align-items: center;      /* align along cross axis */
  gap: 1rem;                /* space between items */
}

justify-content Options

CSS
.nav {
  display: flex;
  justify-content: space-between; /* items at each end */
  /* Other options: */
  /* justify-content: flex-start;  left */
  /* justify-content: flex-end;    right */
  /* justify-content: center;      middle */
  /* justify-content: space-around;equal space around */
}
Flexbox justify-content values

Flex Children

CSS
.child {
  flex: 1;       /* grow to fill available space */
}

.child-fixed {
  flex: 0 0 200px; /* fixed 200px, no grow/shrink */
}
🧭">Build a Nav Bar

Create a nav element with a logo on the left and links on the right using flexbox. Use justify-content: space-between. Make the links display inline using a flex row too.

Quick Check

What CSS property activates flexbox?

Aflex: 1
Bdisplay: flex
Clayout: flex

Which property spaces flex items evenly with space between them?

Aalign-items: space-between
Bflex-direction: space
Cjustify-content: space-between

What does gap do in flexbox?

ASets the font size
BAdds space between flex items
CControls text alignment