New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming CSS Flexbox Layout

Flexbox Layout

🎨 CSS

Master Flexbox for modern responsive layouts.

Lesson 4 of 5 Tutorial
0/5 completed

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

PropertyValues
justify-contentflex-start, center, space-between, space-around, space-evenly
align-itemsflex-start, center, flex-end, stretch
flex-directionrow (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;
.row {
    
}
Expected Output
Children are centred inside .row.

Lesson Nav

Lesson sections