What is the main axis and cross axis in CSS Flexbox ?

In Flexbox, the main axis and cross axis are two fundamental concepts that determine the layout and alignment of the flex container and its items. Flexbox is a layout model in CSS designed for building flexible and efficient user interfaces.

Syntax:

/* Setting up a flex container with flex items */
.container {
display: flex;
flex-direction: row; /* Horizontal main axis */
justify-content: space-between; /* Align items along the main axis */
align-items: center; /* Align items along the cross axis */
}

.item {
flex: 1; /* Flex property to distribute available space among items */
}

Main Axis:

The main axis is the primary axis along which flex items are laid out inside a flex container.

  • Direction: It can be either horizontal (from left to right or right to left) or vertical (from top to bottom or bottom to top), depending on the flex-direction property.
  • Controlled by: The justify-content property controls the alignment of items along the main axis.

Cross Axis:

The cross axis is the axis perpendicular to the main axis inside a flex container.

  • Direction: It is perpendicular to the main axis. If the main axis is horizontal, the cross axis is vertical, and vice versa.
  • Controlled by: The align-items property controls the alignment of items along the cross-axis.