Flexbox and Grid for Layouts
Site Admin
· 11 Sep 2026
· 9 views
Flexbox and Grid for Layouts
Flexbox and CSS Grid are the two modern layout systems in CSS. Flexbox handles one-dimensional layouts (a row or a column). Grid handles two-dimensional layouts (rows and columns together).
Flexbox Basics
Flexbox arranges items along a single axis. The container becomes a flex container and its children become flex items.
.container {
display: flex;
justify-content: space-between; /* Horizontal distribution */
align-items: center; /* Vertical alignment */
gap: 1rem; /* Space between items */
flex-wrap: wrap; /* Allow wrapping */
}
.sidebar {
flex: 1; /* Take equal space */
}
.main-content {
flex: 3; /* Take three times more space */
}
Common Flexbox Patterns
/* Center anything */
.center { display: flex; justify-content: center; align-items: center; }
/* Navbar with logo left and links right */
.navbar { display: flex; justify-content: space-between; }
/* Equal-width columns */
.columns { display: flex; gap: 1rem; }
.column { flex: 1; }
/* Footer pinned to bottom */
body { display: flex; flex-direction: column; min-height: 100vh; }
footer { margin-top: auto; }
CSS Grid Basics
Grid creates two-dimensional layouts with rows and columns:
.grid-layout {
display: grid;
grid-template-columns: 250px 1fr 1fr; /* Sidebar + two columns */
grid-template-rows: auto 1fr auto; /* Header, main, footer */
gap: 1.5rem;
min-height: 100vh;
}
.header { grid-column: 1 / -1; } /* Span all columns */
.sidebar { grid-row: 2; }
.main { grid-column: 2 / 4; grid-row: 2; }
.footer { grid-column: 1 / -1; } /* Span all columns */
Responsive Grid with auto-fit
Grid can create responsive layouts without media queries:
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1.5rem;
}
This automatically adjusts the number of columns based on available width. Each card is at least 280px wide and fills available space.
When to Use Which
Use Flexbox for navigation bars, card rows, centering, and any single-axis layout. Use Grid for page layouts, dashboard grids, and complex two-dimensional designs. Many layouts combine both.
Key Points
- Flexbox handles one-dimensional layouts (row or column).
- CSS Grid handles two-dimensional layouts (rows and columns).
justify-contentaligns along the main axis;align-itemsalong the cross axis.grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))creates responsive grids.- Use Flexbox for simple alignment; Grid for complex page layouts.