Cross Axis
May 20, 2023
The Cross Axis is a term used in web layout design that refers to the perpendicular axis of a flex container from the main axis. The main axis is the direction in which flex items are placed, either horizontally or vertically, depending on the value of the flex-direction property. The cross axis is therefore the opposite direction, perpendicular to the main axis. Understanding the cross axis is crucial to creating flexible web layouts with flexbox.
Purpose
The purpose of the cross axis is to provide a way to define the alignment and spacing of flex items in the opposite direction of the main axis. In other words, it’s the axis that determines how flex items are positioned vertically if the flex-direction
is set to row
, or horizontally if flex-direction
is set to column
.
The cross axis is important because it allows us to create flexible layouts that will adapt to different screen sizes and device orientations. It also provides a way to control the vertical or horizontal spacing between flex items, which is essential for creating visually appealing and well-structured web pages.
Usage
To understand how the cross axis works, let’s take a look at a simple example. Suppose we have a flex container with four flex items, and we want to align the items to the center of the container along the cross axis. We can achieve this by setting the align-items
property to center
.
.container {
display: flex;
align-items: center;
/* other properties */
}
.item {
/* styles for the flex items */
}
In this example, the align-items
property is used to vertically center the flex items within the container along the cross axis. If the flex-direction
is set to row
, this will align the items horizontally, and if it is set to column
, it will align the items vertically.
Another property that affects the cross axis is justify-content
. This property controls the spacing between flex items along the main axis, but it can also be used to distribute extra space along the cross axis if the flex-direction
property is set to row
.
.container {
display: flex;
justify-content: space-between;
align-items: center;
/* other properties */
}
.item {
/* styles for the flex items */
}
In this example, the justify-content
property is used to distribute extra space between the flex items along the main axis, and the align-items
property is used to center the items along the cross axis.
The align-self
property is another property that affects the cross axis. This property allows us to override the default alignment for individual flex items. We can set it to center
, flex-start
, flex-end
, or baseline
, depending on the desired alignment along the cross axis.
.container {
display: flex;
align-items: center;
/* other properties */
}
.item {
align-self: flex-end;
/* other styles for the flex items */
}
In this example, the align-self
property is used to align one of the flex items to the bottom of the container along the cross axis.