CSS Β· Module 19 Β· Lesson 25 of 48

Flexbox Containers & Directions

What is Flexbox?

Imagine you are arranging books on a single bookshelf. You want to align them in a straight line, either side-by-side (Row) or stacked vertically (Column). You want to easily control whether they align to the left side, the right side, or are spaced out evenly to fill the shelf.

In CSS, Flexbox (Flexible Box Layout) is a one-dimensional layout system. It aligns child elements in a single direction (a row or a column). It is designed to scale and space items fluidly, even when their sizes are dynamic or unknown.

  • Flex Container: The parent element configured with display: flex;.
  • Flex Items: The direct child elements inside the flex container.
  • Flex Direction: Determines the main axis along which items are placed.
  • row (default): Placed horizontally (left-to-right).
  • column: Stacked vertically (top-to-bottom).
  • Why does it matter?

    Before Flexbox, aligning elements side-by-side required tricky float hacks or table layouts. Flexbox makes horizontal lists, navigation headers, sidebars, and grid items incredibly simple to build, auto-adjusting their spacing on different screen sizes.

    Syntax Breakdown

  • display: flex; β€” Initializes the flex container.
  • flex-direction: row; β€” Places items side-by-side.
  • flex-direction: column; β€” Stacks items vertically.
  • Flex Item 1
    Flex Item 2

    Common Mistakes

  • Expecting nested grandchildren to flex: Flexbox only affects *direct* children of the container. If you have <div> (flex) -> <ul> -> <li>, the <li> tags will not be affected by the container's flex rulesβ€”only the <ul> will!
  • Using flex on inline tags directly: Inline tags must be converted, though display: flex converts the container to a block-level flex container automatically.
  • Quick Reference

  • display: flex β€” Creates a block-level flex container.
  • flex-direction: row β€” Lays out items horizontally.
  • flex-direction: column β€” Lays out items vertically.
  • Your Task
    Turn `.row-layout` into a flex container using `display: flex;` and set its `flex-direction` to `row`.
    index.html
    Type code above to start the lesson.
    Live Preview