Introduction to Modern CSS Layouts
Creating layouts in CSS has evolved significantly over the last decade. Gone are the days of abusing floats, tables, and inline-blocks to align elements. Modern CSS provides two extremely robust tools: Flexbox and CSS Grid. Although they are often seen as competing layout systems, they are actually complementary and designed to solve different layout challenges.
Flexbox: One-Dimensional Layouts
Flexbox (Flexible Box Layout) is a one-dimensional layout model. It excels at distributing space and aligning items along a single axis (either horizontally in a row or vertically in a column). It is content-driven: elements define their own size, and the flex container wraps them gracefully.
- justify-content: Aligns items along the main axis (flex-start, center, space-between, space-around, space-evenly).
- align-items: Aligns items along the cross axis (stretch, center, flex-start, flex-end).
- flex-wrap: Controls whether the container wraps items into multiple lines when they run out of space.
CSS Grid: Two-Dimensional Layouts
CSS Grid, on the other hand, is a two-dimensional layout model. It allows you to align items along both columns and rows simultaneously. It is layout-driven: the parent container defines the grid columns and rows, and child elements are assigned to specific cells or grid areas.
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
When to Use Flexbox vs. CSS Grid
The general rule of thumb is: use Flexbox when you want to align a set of items in a single direction (e.g., navigation bars, form inputs, button groups) and CSS Grid when you want to design a full-page layout template (e.g., dashboards, complex editorial layouts, card grids).
Conclusion
By combining CSS Grid for the macro-layout and Flexbox for the micro-layout, you can build exceptionally responsive, accessible, and clean modern interfaces without writing a single media query.