CSS
Frontend
Web Design
Tutorial
Beginner
Ask anything about this article
Hi! I've read this article.
What would you like to know?
@farhan
CSS Grid and Flexbox are both powerful layout systems, but they solve different problems. Understanding when to use each one will make your CSS cleaner and more maintainable.
css.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
}
.nav-links {
display: flex;
gap: 2rem;
}
css/* Container */
display: flex;
flex-direction: row | column;
justify-content: flex-start | center | space-between | space-around;
align-items: stretch | center | flex-start | flex-end;
flex-wrap: nowrap | wrap;
gap: 1rem;
/* Children */
flex: 1; /* grow to fill space */
flex-shrink: 0; /* don't shrink */
align-self: center; /* override parent alignment */
order: -1; /* reorder visually */
css.blog-layout {
display: grid;
grid-template-columns: 1fr 300px;
grid-template-rows: auto 1fr auto;
gap: 2rem;
min-height: 100vh;
}
.header { grid-column: 1 / -1; }
.main { grid-column: 1; }
.sidebar { grid-column: 2; }
.footer { grid-column: 1 / -1; }
css/* Container */
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-columns: repeat(3, 1fr);
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
grid-template-rows: auto 1fr auto;
gap: 1rem;
/* Children */
grid-column: 1 / 3; /* span 2 columns */
grid-row: 1 / -1; /* span all rows */
place-self: center; /* center in cell */
css.nav {
display: flex;
justify-content: space-between;
align-items: center;
}
css.center-me {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
css.card {
display: flex;
flex-direction: column;
}
.card-body { flex: 1; } /* Takes remaining space */
.card-footer { margin-top: auto; } /* Sticks to bottom */
css.page {
display: grid;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
grid-template-columns: 250px 1fr;
}
css.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 1.5rem;
}
css.dashboard {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: auto auto 1fr;
gap: 1rem;
}
.chart-big {
grid-column: span 2;
grid-row: span 2;
}
css/* Grid for the overall layout */
.page {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 2rem;
}
/* Flexbox for content within each grid item */
.card {
display: flex;
flex-direction: column;
gap: 1rem;
}
Grid and Flexbox aren't competitors — they're complementary tools. Master both, and you can build any layout imaginable.