Welcome to Day 31 of the 180 Days of Frontend Development Challenge. Today we'll explore Flexbox, the modern CSS layout model that revolutionized how we build interfaces. For comprehensive Flexbox techniques, see the Learn Frontend Development in 180 Days ebook.
Why Flexbox Matters
Flexbox solves common layout problems that previously required:
- Float hacks
- Complex positioning
- JavaScript calculations
- Table-based layouts
Core Concepts
1. Flex Container Setup
.container {
display: flex; /* Establishes flex context */
}
2. Main vs. Cross Axis
-
Main axis: Defined by
flex-direction
(default: horizontal) - Cross axis: Perpendicular to main axis
Essential Flexbox Properties
Container Properties
.container {
flex-direction: row | row-reverse | column | column-reverse;
flex-wrap: nowrap | wrap | wrap-reverse;
justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly;
align-items: stretch | flex-start | flex-end | center | baseline;
align-content: stretch | flex-start | flex-end | center | space-between | space-around;
gap: 10px; /* Space between items */
}
Item Properties
.item {
order: 0; /* Default, can be positive/negative */
flex-grow: 0; /* Ability to grow */
flex-shrink: 1; /* Ability to shrink */
flex-basis: auto; /* Default size */
align-self: auto | flex-start | flex-end | center | baseline | stretch;
}
Practical Examples
Basic Navigation Bar
<nav class="flex-nav">
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Contact</a>
</nav>
.flex-nav {
display: flex;
gap: 1rem;
justify-content: center;
padding: 1rem;
background: #2c3e50;
}
.flex-nav a {
color: white;
text-decoration: none;
padding: 0.5rem 1rem;
}
Card Layout with Flexbox
.card-container {
display: flex;
flex-wrap: wrap;
gap: 20px;
justify-content: center;
}
.card {
flex: 1 1 300px; /* Grow | Shrink | Basis */
max-width: 400px;
padding: 1.5rem;
border: 1px solid #ddd;
border-radius: 8px;
}
Flexbox Best Practices
-
Use shorthand
flex
property
.item {
flex: 1 1 auto; /* flex-grow | flex-shrink | flex-basis */
}
Prefer
gap
over margins for consistent spacingCombine with media queries for responsive layouts
Use
min-width
/max-width
to control flexible items
Exercises
-
Create a responsive navbar that:
- Stacks vertically on mobile
- Displays horizontally on desktop
- Has equal spacing between items
-
Build a media object with:
- Image on left
- Content on right
- Proper vertical alignment
-
Implement a holy grail layout using:
- Header
- Footer
- Three content columns (fixed | fluid | fixed)
What's Next?
Tomorrow (Day 32) dives into CSS Grid, the two-dimensional layout system that complements Flexbox. For advanced Flexbox patterns and real-world use cases, see Chapter 26 in the Learn Frontend Development in 180 Days ebook.
Debugging Tip: Use this CSS to visualize flex containers and items:
.debug-flex {
outline: 2px dashed #3498db;
}
.debug-flex > * {
outline: 2px dashed #e74c3c;
}
Top comments (0)