CSS Flexbox (Flexible Box Layout) is a 1D layout engine designed to align, distribute, and space child elements inside container boxes along a single axis (row or column).
Flexbox operates via parent container properties and child item properties:
/* Flex Container */
.flex-container {
display: flex;
flex-direction: row; /* row | column */
justify-content: space-between;/* main-axis alignment: flex-start | flex-end | center | space-between | space-around */
align-items: center; /* cross-axis alignment: flex-start | flex-end | center | stretch */
flex-wrap: wrap; /* nowrap | wrap */
gap: 1.5rem; /* Spacing between flex items */
}
/* Flex Child Item */
.flex-item {
flex: 1; /* Shorthand for flex-grow: 1, flex-shrink: 1, flex-basis: 0 */
}
Core flexbox properties:
display: flex: Activates flexbox layout on the parent container.flex-direction: Sets main axis direction (row horizontal or column vertical).justify-content: Aligns items along the main axis.align-items: Aligns items along the cross axis.gap: Defines spacing between adjacent flex items.flowchart LR
A["Main Axis (justify-content: space-between)"] --> B["Flex Item 1"]
A --> C["Flex Item 2"]
A --> D["Flex Item 3"]
E["Cross Axis (align-items: center)"] --> B
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Flexbox Demonstration</title>
<style>
.card-grid {
display: flex;
flex-wrap: wrap;
gap: 1.5rem;
}
.card-item {
flex: 1 1 200px; /* Grow, shrink, 200px min basis */
background-color: #1e293b;
padding: 1.5rem;
border-radius: 8px;
border: 1px solid #334155;
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; padding: 2rem;">
<h2>Flexbox Responsive Card Row</h2>
<div class="card-grid">
<div class="card-item">
<h3 style="color: #38bdf8; margin-top: 0;">Card 1</h3>
<p>Flex item expands fluidly.</p>
</div>
<div class="card-item">
<h3 style="color: #38bdf8; margin-top: 0;">Card 2</h3>
<p>Flexbox handles equal height distribution automatically.</p>
</div>
</div>
</body>
</html>
gap instead of margins for flex item spacing: gap: 1rem; sets clean space between flex children without extra margin overrides.flex: 1 for equal-width columns: Makes child columns expand equally to fill remaining container space.flex-direction: column for mobile menus: Toggle flex-direction between row on desktop and column on mobile viewports.Create a CSS class .row with display: flex; justify-content: space-between; align-items: center; gap: 1rem;!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.