CSS Flexbox: Mastering the Container
"Flexbox provides a more efficient way to lay out, align, and distribute space among items in a container, even when their size is unknown or dynamic."
The Core Concept: Two Axes
The most important concept to grasp about Flexbox is that it works on a two-axis system: the Main Axis and the Cross Axis.
When you set display: flex; on a container, the direct children become flex items. By default, the Main Axis flows horizontally (left-to-right), and the Cross Axis flows vertically (top-to-bottom).
Main Axis: Justify-Content
To align items along the Main Axis, we use justify-content. This property determines how the browser distributes extra space along the primary direction of the flex container.
center: Packs items around the center.space-between: Distributes items evenly; the first item is flush with the start, the last is flush with the end.space-around: Distributes items evenly with equal space around them.
Cross Axis: Align-Items
To align items perpendicular to the Main Axis, we use align-items. This is what allows for perfect vertical centering. Note that by default, align-items is set to stretch, which is why flex items automatically expand to fill the container's height!
Wrapping and Gap
Flexbox tries to force all items onto a single line. When items overflow, you can allow them to wrap onto multiple lines using flex-wrap: wrap;.
Finally, ditch the awkward margins. The modern way to add spacing between flex items is the gap property, which intelligently applies space strictly between items, never around the edges of the container.
❓ Frequently Asked Questions
What is the difference between Flexbox and CSS Grid?
Flexbox is one-dimensional. It is designed to lay out elements in a single row (main axis) or a single column. It is ideal for aligning UI components.
CSS Grid is two-dimensional. It handles rows and columns simultaneously, making it better for full-page layouts and complex structures.
How do I perfectly center a div using Flexbox?
This is the most famous use case. Apply these three lines to the parent container (and ensure the container has height):
.parent {
display: flex;
justify-content: center;
align-items: center;
height: 100vh; /* Example */
}Why use `gap` instead of `margin`?
margin often adds unwanted extra space at the end or beginning of a row, requiring pseudo-selectors like :last-child { margin-right: 0 }. Using gap eliminates this problem by inserting space strictly between elements.
