Flexbox β Arranging Layouts in a Single Line
After completing this topic
You will understand the core properties of Flexbox and be able to freely control horizontal/vertical alignment and spacing.
display: flex in a Single Line
.container {
display: flex;
}With just this single line, child elements are arranged horizontally side by side. Compared to the days when we struggled with float or inline-block, this is revolutionary.
Main Axis and Cross Axis
Flexbox has two axes:
Main axis: The direction in which items are placed. The default is horizontal (row). Cross axis: The direction perpendicular to the main axis. The default is vertical.
.container {
display: flex;
flex-direction: row; /* Default: horizontal arrangement */
flex-direction: column; /* Vertical arrangement */
}Changing flex-direction to column makes the main axis vertical.
Main Axis Alignment: justify-content
Determines how to arrange items along the main axis:
.container {
display: flex;
justify-content: flex-start; /* Align to the start (default) */
justify-content: center; /* Align to the center */
justify-content: flex-end; /* Align to the end */
justify-content: space-between; /* Attach to both ends and distribute evenly */
justify-content: space-around; /* Distribute evenly + spacing at both ends */
}space-between is often used to place the logo and menu at the far left and right in a navigation bar.
Cross Axis Alignment: align-items
Determines how to arrange items along the cross axis:
.container {
display: flex;
align-items: stretch; /* Stretch to fit the container height (default) */
align-items: center; /* Align vertically to the center */
align-items: flex-start; /* Align to the top */
align-items: flex-end; /* Align to the bottom */
}Horizontal and Vertical Centering:
.container {
display: flex;
justify-content: center;
align-items: center;
}With these three lines, perfect centering is achieved.
gap β Spacing
.container {
display: flex;
gap: 16px;
}Specifies the spacing between items. In the past, we had to adjust this manually using margins, but with gap, it can be done in a single line. This avoids unnecessary margins after the last item.
flex-wrap β Line Break
.container {
display: flex;
flex-wrap: wrap;
}By default, Flex items are all placed in a single line. If there is not enough space, the items are squeezed. Using flex-wrap: wrap allows items to wrap to the next line when there is insufficient space. This is useful for creating card grids.
flex: 1 β Fill Remaining Space
.sidebar { width: 250px; }
.content { flex: 1; }flex: 1 occupies all the remaining space. This is used to create a fluid content area next to a fixed-width sidebar.
Key Takeaways
display: flexin a single line arranges child elements horizontally side by side.justify-contentaligns along the main axis, andalign-itemsaligns along the cross axis.gapcan be used for spacing, andflex: 1can be used to fill the remaining space.