CSS Flexbox
Learn how to create flexible layouts with CSS Flexbox
🎯 🔄 Layout Made Flexible
- Have you ever struggled to center something or create equal-height columns with CSS?
- Think about app navigation bars. How do they keep the logo on the left and menu items on the right?
- What happens to website layouts when you resize your browser window or rotate your phone?
Learning Objectives
By the end of this lesson, you'll be able to:
- ✓ Understand Understand the Flexbox mental model of containers and items
- ✓ Control flex direction to create row and column layouts
- ✓ Master justify-content for main axis alignment and spacing
- ✓ Use align-items and align-self for cross-axis positioning
- ✓ Implement flex-wrap for responsive multi-line layouts
- ✓ Apply Apply flex-grow, flex-shrink, and flex-basis for flexible sizing
- ✓ Build real-world components like navigation bars and card grids
Flexbox Basics
Flexbox (Flexible Box Layout) is a one-dimensional layout method designed for laying out items in rows or columns. It makes it easier to design flexible responsive layout structures without using float or positioning.
Flex Container
To create a flex container, you set the display property to flex or inline-flex. This establishes a new flex formatting context for the container's direct children, which become flex items.
HTML
<div class="flex-container">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
</div>CSS
/* Basic Flex Container */
.flex-container {
display: flex;
background-color: #f0f0f0;
padding: 10px;
}
.flex-item {
background-color: #3273dc;
color: white;
padding: 20px;
margin: 10px;
text-align: center;
}Result
Flex Items
Flex items are the direct children of a flex container. They automatically arrange themselves according to the flex properties set on the container and can have their own flex properties.
Key properties for flex items include:
flex-grow: Determines how much an item can grow relative to other itemsflex-shrink: Determines how much an item can shrink relative to other itemsflex-basis: Sets the initial main size of an itemflex: Shorthand for flex-grow, flex-shrink, and flex-basisalign-self: Overrides the container's align-items property for specific itemsorder: Controls the order in which items appear
Flex Properties
Flexbox provides several properties to control the layout of flex containers and items. Let's explore the most important ones.
Flex Direction
The flex-direction property establishes the main axis, defining the direction in which flex items are placed in the flex container.
HTML
<div class="flex-container">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
</div>CSS
/* Flex Direction Examples */
.flex-container {
display: flex;
background-color: #f0f0f0;
padding: 10px;
/* Try changing to: row, row-reverse, column, column-reverse */
flex-direction: row;
}
.flex-item {
background-color: #3273dc;
color: white;
padding: 20px;
margin: 10px;
text-align: center;
}Result
Try these values for flex-direction:
Justify Content
The justify-content property aligns flex items along the main axis of the flex container. It helps distribute extra free space when items don't use all available space.
HTML
<div class="flex-container">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
</div>CSS
/* Justify Content Examples */
.flex-container {
display: flex;
background-color: #f0f0f0;
padding: 10px;
height: 200px;
/* Try changing to: flex-start, flex-end, center, space-between, space-around, space-evenly */
justify-content: flex-start;
}
.flex-item {
background-color: #3273dc;
color: white;
padding: 20px;
margin: 10px;
text-align: center;
}Result
Try these values for justify-content:
Align Items
The align-items property defines how flex items are laid out along the cross axis of the flex container. Think of it as the vertical alignment when your flex-direction is row.
HTML
<div class="flex-container">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
</div>CSS
/* Align Items Examples */
.flex-container {
display: flex;
background-color: #f0f0f0;
padding: 10px;
height: 200px;
/* Try changing to: flex-start, flex-end, center, stretch, baseline */
align-items: stretch;
}
.flex-item {
background-color: #3273dc;
color: white;
padding: 20px;
margin: 10px;
text-align: center;
}Result
Try these values for align-items:
Practical Examples
Let's look at some practical examples of how Flexbox can be used to create common UI patterns.
Card Layout
Card layouts are another common pattern that benefits from Flexbox. You can easily create responsive card grids that adjust to different screen sizes.
HTML
<div class="card-container">
<div class="card">
<img src="https://via.placeholder.com/150" alt="Card image">
<div class="card-content">
<h3>Card Title 1</h3>
<p>This is some sample text for the first card.</p>
<button>Learn More</button>
</div>
</div>
<div class="card">
<img src="https://via.placeholder.com/150" alt="Card image">
<div class="card-content">
<h3>Card Title 2</h3>
<p>This is some sample text for the second card.</p>
<button>Learn More</button>
</div>
</div>
<div class="card">
<img src="https://via.placeholder.com/150" alt="Card image">
<div class="card-content">
<h3>Card Title 3</h3>
<p>This is some sample text for the third card.</p>
<button>Learn More</button>
</div>
</div>
</div>CSS
/* Card Layout with Flexbox */
.card-container {
display: flex;
flex-wrap: wrap;
gap: 20px;
justify-content: center;
}
.card {
display: flex;
flex-direction: column;
width: 300px;
border: 1px solid #ddd;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.card img {
width: 100%;
height: 150px;
object-fit: cover;
}
.card-content {
padding: 15px;
display: flex;
flex-direction: column;
flex-grow: 1;
}
.card-content h3 {
margin-top: 0;
}
.card-content button {
margin-top: auto;
padding: 8px 16px;
background-color: #3273dc;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.card-content button:hover {
background-color: #2366d1;
}Result
Card Title 1
This is some sample text for the first card.
Card Title 2
This is some sample text for the second card.
Card Title 3
This is some sample text for the third card.
Further Resources
- CSS-Tricks: A Complete Guide to Flexbox
- MDN: Basic Concepts of Flexbox
- Flexbox Froggy - A game for learning Flexbox
⏸️ Pause & Check: Do You Understand?
Before moving forward, can you answer these?
- What happens when you set display: flex on a container?
- How do the main axis and cross axis differ in Flexbox?
- When would you use justify-content vs align-items?
- What do flex-grow, flex-shrink, and flex-basis control?
Check Your Answers
- Setting display: flex establishes a flex formatting context. The element becomes a flex container, its direct children become flex items, and layout shifts to using the main and cross axes for alignment and distribution.
- The main axis follows flex-direction (row by default). justify-content aligns items along the main axis. The cross axis is perpendicular to the main axis; align-items and align-content control alignment along it. Changing flex-direction swaps the axes.
- justify-content distributes extra space along the main axis (left/right in rows, top/bottom in columns). align-items controls alignment on the cross axis (vertical in rows, horizontal in columns). Use justify-content for spacing between items, align-items for baseline, center, or stretch alignment.
- flex-grow defines how extra space is distributed among items, flex-shrink controls how items shrink when space is limited, and flex-basis sets the initial size before growing or shrinking. Combined as flex: grow shrink basis, they create responsive components.
How confident are you with this concept?
😕 Still confused | 🤔 Getting there | 😊 Got it! | 🎉 Could explain it to a friend!
Practical Application: Site-Wide Flexbox Implementation
Now that you understand the fundamentals of Flexbox, it's time to apply these concepts to create cohesive, responsive layouts for the two websites we've been building throughout this course: The Black Swan Bistro restaurant site and Alex Chen's Personal Profile Page.
The Black Swan Bistro Style Guide
For The Black Swan Bistro restaurant site, we'll use Flexbox to create an elegant, appetizing layout that showcases the restaurant's offerings and ambiance.
Layout Structure
/* Main Layout Structure */
body {
display: flex;
flex-direction: column;
min-height: 100vh; /* Full viewport height */
font-family: 'Playfair Display', serif;
color: #333;
}
header, footer {
flex-shrink: 0; /* Prevent header/footer from shrinking */
background-color: #1a1a1a;
color: #f8f8f8;
}
main {
flex: 1; /* Take up remaining space */
display: flex;
flex-direction: column;
padding: 2rem;
}
/* Responsive container */
.container {
width: 100%;
max-width: 1200px;
margin: 0 auto;
padding: 0 1rem;
}Navigation
/* Navigation Bar */
.bistro-nav {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
background-color: #1a1a1a;
}
.bistro-logo {
font-family: 'Playfair Display', serif;
font-size: 1.8rem;
font-weight: bold;
color: #f8f8f8;
}
.bistro-nav-links {
display: flex;
gap: 2rem;
list-style: none;
margin: 0;
padding: 0;
}
.bistro-nav-links a {
color: #f8f8f8;
text-decoration: none;
font-size: 1.1rem;
transition: color 0.3s ease;
}
.bistro-nav-links a:hover {
color: #d4af37; /* Gold accent color */
}
/* Responsive navigation for mobile */
@media (max-width: 768px) {
.bistro-nav {
flex-direction: column;
padding: 1rem;
}
.bistro-nav-links {
margin-top: 1rem;
width: 100%;
justify-content: space-around;
}
}Menu Section
/* Menu Section */
.menu-section {
display: flex;
flex-direction: column;
margin: 3rem 0;
}
.menu-categories {
display: flex;
justify-content: center;
gap: 1.5rem;
margin-bottom: 2rem;
}
.menu-category {
padding: 0.5rem 1.5rem;
border: 1px solid #d4af37;
border-radius: 30px;
cursor: pointer;
transition: all 0.3s ease;
}
.menu-category.active, .menu-category:hover {
background-color: #d4af37;
color: #fff;
}
.menu-items {
display: flex;
flex-wrap: wrap;
gap: 2rem;
}
.menu-item {
display: flex;
flex-direction: column;
flex-basis: calc(50% - 2rem);
min-width: 300px;
padding: 1.5rem;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
transition: transform 0.3s ease;
}
.menu-item:hover {
transform: translateY(-5px);
}
.menu-item-header {
display: flex;
justify-content: space-between;
margin-bottom: 1rem;
border-bottom: 1px dotted #d4af37;
padding-bottom: 0.5rem;
}
.menu-item-name {
font-weight: bold;
font-size: 1.2rem;
}
.menu-item-price {
color: #d4af37;
font-weight: bold;
}
.menu-item-description {
font-style: italic;
color: #666;
}
/* Responsive adjustments */
@media (max-width: 768px) {
.menu-item {
flex-basis: 100%;
}
.menu-categories {
flex-wrap: wrap;
}
}Personal Profile Page Style Guide
For Alex Chen's Personal Profile Page, we'll use Flexbox to create a clean, professional layout that highlights the bio, skills, interests, and contact details.
Layout Structure
/* Main Layout Structure */
body {
display: flex;
flex-direction: column;
min-height: 100vh;
font-family: 'Open Sans', sans-serif;
color: #333;
background-color: #f9f9f9;
}
.site-header {
background-color: #2c3e50;
color: white;
}
.site-content {
flex: 1;
display: flex;
gap: 2rem;
padding: 2rem;
}
.main-content {
flex: 2;
}
.sidebar {
flex: 1;
background-color: #f8f9fa;
padding: 1.5rem;
border-radius: 8px;
}
/* Responsive layout */
@media (max-width: 768px) {
.site-content {
flex-direction: column;
padding: 1rem;
}
.main-content {
padding-right: 0;
margin-bottom: 2rem;
}
}Skills and Interest Cards
/* Skills and Interest Cards */
.skills-list {
display: flex;
flex-wrap: wrap;
gap: 1rem;
list-style: none;
padding: 0;
}
.skill-item,
.interest-card {
display: flex;
flex-direction: column;
flex-basis: calc(33.333% - 1rem);
min-width: 200px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
background-color: white;
padding: 1.25rem;
}
.interest-card:hover {
transform: translateY(-5px);
}
.skill-item {
align-items: center;
justify-content: center;
font-weight: 600;
}
.interest-row {
display: flex;
gap: 1rem;
}
.interest-card img {
width: 100%;
border-radius: 6px;
margin-bottom: 1rem;
}
/* Responsive adjustments */
@media (max-width: 992px) {
.skill-item,
.interest-card {
flex-basis: calc(50% - 1rem);
}
}
@media (max-width: 576px) {
.skill-item,
.interest-card {
flex-basis: 100%;
}
}Navigation and Project Cards
/* Navigation and Project Cards */
.site-nav {
display: flex;
justify-content: space-between;
align-items: center;
gap: 2rem;
}
.nav-links {
display: flex;
gap: 1rem;
}
.project-row {
display: flex;
gap: 1rem;
margin-top: 2rem;
}
.project-card {
flex: 1;
display: flex;
flex-direction: column;
padding: 1.25rem;
background: white;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0,0,0,0.08);
}
/* Responsive adjustments */
@media (max-width: 768px) {
.site-nav,
.project-row {
flex-direction: column;
}
.nav-links {
flex-wrap: wrap;
}
}Challenge: Apply Flexbox to Your Sites
Now it's your turn to put these concepts into practice! Take the style guides above and apply them to The Black Swan Bistro and Personal Profile Page projects you've been building throughout this course.
Your task:
- Implement the layout structure for both sites using Flexbox
- Create responsive navigation bars that adapt to different screen sizes
- For The Black Swan Bistro:
- Build the menu section with categories and menu items
- Create a responsive layout for showcasing special dishes or events
- For the Personal Profile Page:
- Build a horizontal skills list using Flexbox
- Create a navigation bar and a row of interest or project cards
- Test your layouts on different screen sizes and make adjustments as needed
Remember to use the browser's developer tools to inspect and debug your layouts. The Flexbox properties we've covered in this tutorial will give you all the tools you need to create professional, responsive designs for both websites.
Bonus challenge: Add animations to your layouts using CSS transitions when elements are hovered or focused, such as menu items highlighting on The Black Swan Bistro site or profile cards lifting slightly on the Personal Profile Page.
Lesson checkpoint
Test Your Knowledge
Strengthen your understanding of Flexbox by answering the quiz below.
Flexbox Quiz
Test your understanding of Flexbox concepts.
Lesson Complete: What You Learned
Key Takeaways:
- Flex containers are created with display: flex/inline-flex and control layout of direct children
- flex-direction sets the main axis; justify-content and align-items manage spacing across axes
- flex-wrap enables multi-line layouts; gap adds spacing without margins
- flex-grow, flex-shrink, and flex-basis define how items scale in responsive layouts
- Align-self overrides alignment per item; order rearranges items without changing HTML
Learning Objectives Review:
Look back at what you set out to learn. Can you now:
- ✅ Create flexible navigation bars, cards, and page sections with Flexbox Check!
- ✅ Control alignment, spacing, and wrapping along main/cross axes Got it!
- ✅ Use flex shorthand to build responsive components quickly Can explain it!
- ✅ Apply Flexbox to real projects like Black Swan Bistro and a Personal Profile Page Could teach this!
- ✅ Debug Flexbox layouts using browser DevTools Check!
If you can confidently answer "yes" to most of these, you're ready to move on!
Think & Reflect:
Axis Awareness
- What happens to alignment when you switch flex-direction to column?
- How can you use gap and justify-content together to manage spacing?
Responsive Mindset
- How do flex properties help components adapt across breakpoints?
- When do you need media queries in addition to Flexbox?
🤔 Real-World Test:
Product teams use Flexbox for navigation bars, dashboards, pricing cards, and countless UI components. Frameworks like Bootstrap and Tailwind rely on Flexbox under the hood. Mastering Flexbox makes custom component work faster and helps you debug framework utilities with confidence.
Design systems often start with Flexbox primitives (stacks, clusters, sidebar layouts). Your ability to implement these patterns accurately ensures consistency across apps.
🎯 Looking Ahead:
Next up is the modern CSS module, where you will learn advanced techniques (Grid, clamp(), container queries) building on Flexbox fundamentals. Continue practicing by recreating real-world layouts—Flexbox is foundational to all responsive design work.
Recommended Next Steps
Continue Learning
Ready to move forward? Continue with the next tutorial in this series:
Responsive DesignRelated Topics
Explore these related tutorials to expand your knowledge:
Practice Projects
Apply what you've learned with these hands-on projects:
Additional Resources
Deepen your understanding with these helpful resources:
- MDN: Flexbox - Guide to CSS Flexbox layout
Progress tracking is disabled. Enable it in to track your completed tutorials.
Cookie Settings