CSS Flexbox: Taming the Layout
Say goodbye to clearing floats and complex table layouts. Flexbox (Flexible Box Layout) is a one-dimensional layout method for arranging items in rows or columns. Items flex to fill additional space and shrink to fit into smaller spaces.
The Container vs. The Items
Flexbox operates on a parent-child relationship. You define a Flex Container by setting display: flex or display: inline-flex. As soon as you do this, all direct children of that container magically become Flex Items.
Properties are split between the container (governing the overall layout, direction, and spacing) and the items (governing their individual size and order).
The Two Axes
Unlike traditional CSS, Flexbox is direction-agnostic. It relies on two axes: the Main Axis and the Cross Axis.
- Main Axis: Defined by
flex-direction. If the direction isrow, the main axis is horizontal. If it'scolumn, it's vertical. Alignment here is handled byjustify-content. - Cross Axis: Perpendicular to the main axis. Alignment here is handled by
align-itemsandalign-content.
Wrapping and Gaps
By default, flex items will try to fit onto one line. You can change this with flex-wrap: wrap, which allows items to break into multiple lines. To add spacing between items, modern CSS gives us the gap property, eliminating the need for complex margin hacks.
View Flex Item Properties+
flex-grow: Dictates what amount of the available space inside the flex container the item should take up.
flex-shrink: Dictates how much the item will shrink relative to the rest of the flex items when space is tight.
flex-basis: Defines the default size of an element before the remaining space is distributed.
❓ Frequently Asked Questions
What is the difference between Flexbox and CSS Grid?
Flexbox is one-dimensional. It is designed for laying out items in a single dimension at a time: either a row OR a column.
CSS Grid is two-dimensional. It is designed for complex layouts in two dimensions: rows AND columns simultaneously. As a general rule: use Flexbox to align items within a component, and Grid for the main page layout.
Why are my elements squishing when the container is small?
By default, flex items have the property flex-shrink: 1, which means they will shrink to avoid overflowing their container on a single line.
To fix this, you can allow them to wrap to the next line using flex-wrap: wrap; on the container, or prevent a specific element from shrinking by using flex-shrink: 0; on that element.
How do I perfectly center an element in the middle of the screen?
The famous "Holy Grail" of CSS centering now requires only 3 lines in the parent container (assuming it has full height):
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}