CSS β Layouts & Cool Effects
intermediate25 XP
Flexbox β The Magic Layout Tool!
Arrange elements side-by-side, centre things perfectly, and build nav bars and card grids with flexbox!
Flexbox β Arranging Elements Like a Pro! π¦
Flexbox is CSS's superpower for layouts. It makes arranging elements side-by-side, centring things, and building grids incredibly easy!
Without Flexbox vs With Flexbox
Without flexbox, everything stacks vertically. With flexbox, you control everything!
CSS
.container {
display: flex; /* β this one line activates flexbox! */
}Main Flexbox Properties
CSS
.container {
display: flex;
/* Direction */
flex-direction: row; /* left to right (default) */
flex-direction: column; /* top to bottom */
/* Horizontal alignment */
justify-content: flex-start; /* pack to start */
justify-content: center; /* centre everything */
justify-content: space-between;/* even gaps between items */
justify-content: space-around; /* even gaps around items */
/* Vertical alignment */
align-items: center; /* vertically centred */
align-items: flex-start; /* align to top */
align-items: stretch; /* fill height (default) */
/* Wrapping (onto next line if too many items) */
flex-wrap: wrap;
/* Gap between items */
gap: 16px;
}π Example 1: Centring Anything
The holy grail of CSS β perfectly centring an element:
CSS
.hero {
display: flex;
justify-content: center; /* horizontal centre */
align-items: center; /* vertical centre */
height: 100vh; /* full screen height */
}HTML
<div class="hero">
<h1>I'm perfectly centered! π―</h1>
</div>π Example 2: Navigation Bar
HTML
<nav class="navbar">
<div class="logo">π KCA</div>
<ul class="nav-links">
<li><a href="#">Home</a></li>
<li><a href="#">Learn</a></li>
<li><a href="#">Badges</a></li>
</ul>
</nav>CSS
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 32px;
background-color: #6d28d9;
color: white;
}
.nav-links {
display: flex;
gap: 24px;
list-style: none;
}π Example 3: Card Grid
CSS
.card-grid {
display: flex;
flex-wrap: wrap; /* wraps to next line */
gap: 20px;
justify-content: center;
}
.card {
flex: 0 0 280px; /* each card is 280px wide */
}Flexbox is used on almost every modern website β YouTube, Netflix, Instagram all use it! π¬
Quick check
01/3
Which CSS property activates flexbox on a container?