Flex Direction

 Flexbox flex-direction Explained

HTML’s Default Flow

  • Inline elements → Sit side by side until there’s no more space.

  • Block elements → Stack one on top of another (vertically).

👉 This is the normal HTML flow: from top to bottom.


The Magic of Flexbox

When we apply display: flex; to a parent container, all its child elements automatically align in a single row (row-wise) → from left to right.

The reason is the flex-direction property, which defaults to row.


Main Axis vs Cross Axis

The most important Flexbox concept is understanding the main axis and cross axis.

  • When flex-direction: row;

    • Main axis = left → right (horizontal)

    • Cross axis = top → bottom (vertical)

  • When flex-direction: column;

    • Main axis = top → bottom (vertical)

    • Cross axis = left → right (horizontal)

👉 So, the direction of the main axis depends on the value of flex-direction.


flex-basis (Sizing Along the Main Axis)

The flex-basis property controls how much space a child element should take along the main axis.

  • If flex-direction: row;flex-basis controls the width.

  • If flex-direction: column;flex-basis controls the height.

Example:

.container > * { flex-basis: 100px; }
  • In row, each child’s width will be 100px.

  • In column, each child’s height will be 100px.


Selecting Children with CSS Combinators

Suppose your container has multiple <div> elements, but they don’t have individual classes.
You can target them using the child combinator:

.container > * { flex-basis: 100px; }

Here:

  • .container = parent container

  • > = child combinator (selects only direct children)

  • * = universal selector (selects all elements)


inline-flex vs flex

  • display: flex; → The container takes up the full width of the parent.

  • display: inline-flex; → The container only takes up as much space as needed.


Summary

  • flex-direction sets the main axis → either row or column.

  • Understanding main axis and cross axis is crucial because most Flexbox properties depend on them.

  • flex-basis controls child element size along the main axis.

  • Use .container > * to easily target all direct children.

Comments