CSS โ Lesson 4
Flexbox
Modern one-dimensional layout system.
Flexbox
Flexbox is a one-dimensional layout system that makes it easy to align and distribute items within a container.
Setting Up Flexbox
.container {
display: flex;
}
Main Axis vs Cross Axis
- Main axis: horizontal by default (flex-direction: row)
- Cross axis: vertical (perpendicular to main axis)
Flex Direction
.container {
flex-direction: row; /* default: left to right */
flex-direction: column; /* top to bottom */
flex-direction: row-reverse; /* right to left */
}
Justify Content (Main Axis)
.container {
justify-content: center; /* center items */
justify-content: space-between; /* equal space between */
justify-content: space-around; /* space around each item */
justify-content: flex-end; /* align to end */
}
Align Items (Cross Axis)
.container {
align-items: center; /* vertically center */
align-items: stretch; /* stretch to fill height */
align-items: flex-start; /* align to top */
align-items: flex-end; /* align to bottom */
}
Centering with Flexbox
The most common flexbox use case: perfectly center an element both horizontally and vertically.
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh; /* full viewport height */
}
Flex Wrap
Control whether items wrap to a new line when they overflow.
.container {
flex-wrap: wrap; /* allow wrapping */
flex-wrap: nowrap; /* default: no wrap */
}
Gap
Add spacing between flex items without using margins.
.container {
display: flex;
gap: 16px; /* space between items */
}
Tip: Flexbox is perfect for navigation bars, card layouts, centering content, and arranging items in a row or column.
Practice what you learned in the Deoit Editor โ a free, browser-based code editor.
Open Editor โ