Flexbox Layout
Flexbox is the modern way to create layouts in CSS. It makes it easy to align and distribute space.
.container {
display: flex;
justify-content: space-between; /* horizontal */
align-items: center; /* vertical */
gap: 20px; /* space between items */
flex-wrap: wrap; /* wrap to next line */
}
.item {
flex: 1; /* grow to fill space equally */
}
Common Values
| Property | Values |
|---|---|
| justify-content | flex-start, center, space-between, space-around, space-evenly |
| align-items | flex-start, center, flex-end, stretch |
| flex-direction | row (default), column, row-reverse, column-reverse |
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial; margin: 0; }
.navbar {
display: flex;
align-items: center;
padding: 15px 30px;
background: #5E256D;
color: white;
}
.navbar .brand { font-size: 1.3rem; font-weight: bold; }
.navbar .links { margin-left: auto; display: flex; gap: 20px; }
.navbar .links a { color: white; text-decoration: none; }
.cards {
display: flex;
gap: 20px;
padding: 30px;
flex-wrap: wrap;
}
.card {
flex: 1;
min-width: 200px;
background: #f8fafc;
border: 1px solid #e2e8f0;
border-radius: 12px;
padding: 20px;
text-align: center;
}
</style>
</head>
<body>
<nav class="navbar">
<span class="brand">MySite</span>
<div class="links">
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Contact</a>
</div>
</nav>
<div class="cards">
<div class="card"><h3>Card 1</h3><p>Content here</p></div>
<div class="card"><h3>Card 2</h3><p>Content here</p></div>
<div class="card"><h3>Card 3</h3><p>Content here</p></div>
</div>
</body>
</html>
Exercises
Exercise 1. Centre Items with Flexbox
Medium
Make .row a flex container and centre its children horizontally.
Use exactly: display: flex; and justify-content: center;
Use exactly: display: flex; and justify-content: center;
.row {
}
Expected Output
Children are centred inside .row.