CSS Β· Module 19 Β· Lesson 26 of 48

Justification & Alignment

What is Flexbox Alignment?

Imagine organizing students for a class photo. You can arrange them horizontally along the bench, centering the group or spacing them out evenly (Justify Content). You can also adjust their heights, centering shorter and taller students relative to the bench midline (Align Items).

In Flexbox, we align elements along two axes:

  • Main Axis (the direction set by flex-direction): Aligned using justify-content.
  • Cross Axis (perpendicular to the main axis): Aligned using align-items.
  • Common options for justify-content:

  • flex-start (default): Groups items at the beginning.
  • flex-end: Groups items at the end.
  • center: Centers items.
  • space-between: Spaces items out, putting first item at start and last at end.
  • space-around / space-evenly: Distributes empty spaces.
  • Common options for align-items:

  • stretch (default): Stretches items to fill parent height.
  • center: Centers items vertically.
  • flex-start / flex-end: Aligns to top or bottom.
  • Why does it matter?

    Flexbox alignment makes vertical centeringβ€”the historical bane of CSS developersβ€”trivially easy. Writing justify-content: center; and align-items: center; on a container perfectly centers any child element both horizontally and vertically.

    Syntax Breakdown

  • justify-content: center; β€” Centers items horizontally (in a row layout).
  • align-items: center; β€” Centers items vertically (in a row layout).
  • Left
    Right

    Common Mistakes

  • Confusing justify-content and align-items: Remember that justify-content always aligns along the main axis. If you set flex-direction: column;, the main axis is now vertical! This means justify-content will now control *vertical* spacing, and align-items will control *horizontal* spacing!
  • Quick Reference

  • justify-content β€” Aligns items along the main axis.
  • align-items β€” Aligns items along the cross axis.
  • space-between β€” Maximize space between items.
  • Your Task
    Align the contents of `.align-box` to be centered horizontally and vertically using `justify-content: center;` and `align-items: center;`.
    index.html
    Type code above to start the lesson.
    Live Preview