CSS for Web Development

0% completed

Previous
Next
Main axis and cross axis

Flexbox makes aligning and distributing space among items easier. The key concept in flexbox is understanding the two axes: the main axis and the cross axis.

  • Main Axis:

    • The axis in which the flex items are laid out.
    • Its direction is set by the flex-direction property (default is row, meaning left to right).
  • Cross Axis:

    • Perpendicular to the main axis.
    • In a row layout, the cross axis runs vertically; in a column layout, it runs horizontally.
Image

Knowing the difference between these axes helps you control the alignment and distribution of your flex items precisely.

Syntax

Follow the code block below to create a basic flex container and see how the axes work:

/* Set up a flex container */ .container { display: flex; /* Enables flexbox layout */ flex-direction: row | column; /* Defines the main axis direction */ }

Explanation:

  • display: flex;
    • Turns the container into a flex container.
  • flex-direction:
    • When set to row (default), items are arranged along the horizontal (main) axis and the vertical direction becomes the cross axis.
    • When set to column, items are arranged along the vertical (main) axis and the horizontal direction becomes the cross axis.

Example 1: Main Axis in Row Direction

In this example, the flex container arranges its items in a row (default behavior). The main axis runs horizontally from left to right, while the cross axis runs vertically.

HTML

. . . .

Explanation:

  • Main Axis:
    • In the .container, items are arranged from left to right along the horizontal main axis.
  • Cross Axis:
    • The vertical direction acts as the cross axis, which you might control with properties like align-items.
  • Outcome:
    • The three items appear side by side in a row.

Example 2: Changing the Main and Cross Axis with flex-direction

In this example, we change the flex-direction to column. Now, the main axis runs vertically from top to bottom, while the cross axis runs horizontally.

HTML

. . . .

Explanation:

  • Main Axis:
    • In this container with flex-direction: column, the items stack vertically from top to bottom.
  • Cross Axis:
    • The horizontal direction now serves as the cross axis.
  • Outcome:
    • The three items appear stacked on top of each other, with the container's height accommodating the vertical main axis.

This lesson helps you understand the core concepts of flexbox by distinguishing between the main axis and the cross axis. With these fundamentals, you are ready to explore how other container and item properties work in flexbox layouts.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next