Understanding Main Axis versus Cross Axis
Take note of the main axis and cross axis in a flex container:
In the illustration, the main axis is horizontal while the cross axis is vertical, representing the default orientations for a flex container.
However, these orientations can be interchanged using the flex-direction
property.
/* main axis horizontal, cross axis vertical */
flex-direction: row;
flex-direction: row-reverse;
/* main axis vertical, cross axis horizontal */
flex-direction: column;
flex-direction: column-reverse;
(Note that the cross axis is always perpendicular to the main axis.)
Explanation of the justify-content Property (applicable to main axis only)
The justify-content
property aligns flex items along the main axis within the flex container.
With the container set to flex-direction: row
, resulting in a horizontal main axis, utilizing justify-content: center
will align items accordingly.
Conversely, if the container has flex-direction: column
defined, the main axis is now vertical, causing justify-content
to position items up and down as opposed to left and right.
When there is limited height defined, the effects of justify-content
may not be visible since elements default to an auto height when no specific value is provided. However, adjusting the container's height will showcase the impact.
align-* Properties (operating on cross axis exclusively)
align-self
, align-items
, and align-content
properties affect the alignment of flex items along a flex container's cross axis, which remains perpendicular to the main axis.
Given a vertical main axis, the align-*
properties will control the alignment of items from left to right. This explains why align-self
was effective in centering your divs.
Key Point: Depending on the defined flex-direction
, the main axis and cross axis interchange roles along with their corresponding properties.
Recommended Approach
To achieve brevity in your code, the following snippet suffices:
.main {
display: flex;
flex-direction: column;
align-items: center;
}
Further insights: Exploring the Absence of "justify-items" and "justify-self" Properties in CSS Flexbox