CSS Foundations

Lesson 3 of 6

Flexbox: One-Dimensional Layouts

Flexbox arranges items along a single line, row or column, and is the workhorse for navbars, toolbars, cards, and centering content.

.nav {
  display: flex;
  flex-direction: row;      /* default: left to right */
  justify-content: space-between; /* spacing along the main axis */
  align-items: center;      /* alignment along the cross axis */
  gap: 16px;
}
HTML

The two axes

Flexbox thinks in terms of a main axis (the direction set by flex-direction) and a cross axis (perpendicular to it).

PropertyControlsCommon values
justify-contentSpacing along the main axisflex-start, center, space-between, space-around
align-itemsAlignment along the cross axisflex-start, center, stretch
flex-wrapWhether items wrap to new linesnowrap (default), wrap
gapSpace between itemsany length, e.g. 16px

Sizing individual items

.sidebar { flex: 0 0 250px; } /* never grow, never shrink, fixed 250px */
.content { flex: 1; }         /* grow to fill remaining space */

flex: grow shrink basis controls how a specific child behaves inside the flex container, flex: 1 is shorthand for "take an equal share of whatever space is left".

TIP

Centering something perfectly, both horizontally and vertically, used to be a running joke in CSS. With Flexbox it's three lines: display: flex; justify-content: center; align-items: center;.

📝 Flexbox Quiz

Passing score: 70%
  1. 1.Which property controls spacing of flex items along the main axis?

  2. 2.By default, flex items will wrap onto new lines when they run out of horizontal space.

  3. 3.To turn any element into a flex container, you set display: ____.