Mastering CSS Grid and Flexbox: A Complete Guide
CSS Grid and Flexbox are two of the most powerful layout systems in modern CSS. While they can both be used for layout, they serve different purposes and excel in different scenarios.
Flexbox is designed for one-dimensional layouts (either rows or columns), while CSS Grid is designed for two-dimensional layouts (rows and columns simultaneously).
Flexbox makes it easy to create flexible, responsive layouts. Here’s a basic example:
.container {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
}display: flex - Enables flexboxjustify-content - Aligns items along the main axisalign-items - Aligns items along the cross axisflex-direction - Sets the direction of the flex containerflex-wrap - Allows items to wrap to new linesCSS Grid provides a powerful way to create complex layouts with minimal code:
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
}display: grid - Enables CSS Gridgrid-template-columns - Defines column sizesgrid-template-rows - Defines row sizesgap - Sets spacing between grid itemsgrid-template-areas - Creates named grid areasThe real power comes from combining both layout systems. Use Grid for the overall page structure and Flexbox for the content within grid items.
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
}
.card {
display: flex;
flex-direction: column;
justify-content: space-between;
}Start with mobile layouts and progressively enhance for larger screens:
.container {
display: flex;
flex-direction: column;
}
@media (min-width: 768px) {
.container {
flex-direction: row;
}
}.responsive-grid {
display: grid;
grid-template-columns: 1fr;
gap: 20px;
}
@media (min-width: 768px) {
.responsive-grid {
grid-template-columns: repeat(2, 1fr);
}
}
@media (min-width: 1024px) {
.responsive-grid {
grid-template-columns: repeat(3, 1fr);
}
}.holy-grail {
display: grid;
grid-template-areas:
"header header header"
"nav main aside"
"footer footer footer";
grid-template-columns: 200px 1fr 200px;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
}.masonry {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
grid-auto-rows: 0;
grid-auto-flow: dense;
}will-change sparinglycontain property for isolated layoutsBoth CSS Grid and Flexbox have excellent browser support:
Mastering CSS Grid and Flexbox opens up endless possibilities for creating modern, responsive layouts. The key is understanding when to use each and how to combine them effectively.
Remember: Flexbox for components, Grid for layouts, and always test on real devices!