Codetainer LogoCodetainer Acad

Lessons

Lesson 9: Flexbox Fundamentals

πŸ“¦ Lesson 9: Flexbox Fundamentals

Flexbox is a powerful layout module in CSS that makes it easy to design flexible and responsive layout structures β€” especially when you need to align items in a row or column.


1. The Flex Container

To activate Flexbox, apply display: flex; to a container element. This makes all its direct children flexible items.

.container {
  display: flex;
}

2. Direction of Items: flex-direction

You control the direction of the layout with flex-direction. It can be:

  • row – horizontal (default)
  • row-reverse – horizontal, reversed
  • column – vertical
  • column-reverse – vertical, reversed
.container {
  display: flex;
  flex-direction: row;
}

3. Main Axis Alignment: justify-content

Controls spacing and alignment along the main axis:

  • flex-start – start of container
  • center – center of container
  • space-between – even gaps
  • space-around – equal space around items
  • space-evenly – equal space everywhere
.container {
  justify-content: space-between;
}

4. Cross Axis Alignment: align-items

Aligns items vertically (if flex-direction: row):

  • stretch – (default) fill the container
  • flex-start – top of container
  • center – vertically centered
  • flex-end – bottom of container
.container {
  align-items: center;
}

5. Spacing Items: gap

Add spacing between flex items using gap:

.container {
  gap: 16px;
}

6. Controlling Item Growth

You can control how items grow or shrink with:

  • flex-grow – defines how much a flex item should grow
  • flex-shrink – defines how items shrink if needed
  • flex-basis – initial size of the item before growing/shrinking
.item {
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: 200px;
}

7. Wrap It Up: flex-wrap

By default, Flexbox does not wrap. Use flex-wrap if items overflow.

.container {
  flex-wrap: wrap;
}

βœ… Recap

  • Start with display: flex;
  • Choose direction with flex-direction
  • Align items using justify-content and align-items
  • Use gap for spacing
  • Control item sizes with flex-grow, flex-shrink, and flex-basis

Flexbox is a layout cheat code. Get used to it, and layout hell becomes layout heaven. Up next, we’ll dive into Flexbox Alignment and Wrapping .

CodetainerAcad