Lesson 45 +10 XP

Flex

Flex

Bootstrap provides a full set of flexbox utilities. Add .d-flex to an element to make it a flex container, then use the flex utilities on it and its children.

Basic flex container

<div class="d-flex bg-light">
  <div class="p-2 bg-primary text-white">Item 1</div>
  <div class="p-2 bg-success text-white">Item 2</div>
</div>

Direction

  • .flex-row (default) items in a row.
  • .flex-row-reverse row in reverse.
  • .flex-column items stacked vertically.
  • .flex-column-reverse column in reverse.
<div class="d-flex flex-column">
  <div class="p-2">Top</div>
  <div class="p-2">Bottom</div>
</div>

Justify content (horizontal)

  • .justify-content-start items at the start.
  • .justify-content-center items centered.
  • .justify-content-end items at the end.
  • .justify-content-between space between items.
  • .justify-content-around space around items.
<div class="d-flex justify-content-center">
  <div class="p-2">Centered</div>
</div>

Align items (vertical)

  • .align-items-start
  • .align-items-center
  • .align-items-end

Order and fill

  • .flex-fill makes items fill the row equally.
  • .order-0 to .order-5 reorders items.
  • .flex-grow-1 lets an item grow.

Responsive flex

Add breakpoints to flex classes, like .d-md-flex or .flex-md-row, to change layout at different screen sizes.

TL;DR

  • Start with .d-flex.
  • .flex-row / .flex-column set direction.
  • .justify-content-* aligns horizontally.
  • .align-items-* aligns vertically.
  • Flex utilities work responsively with breakpoints.