GK SOLUTIONS
AI • IoT • Arduino • Projects & Tutorials
DEFEAT THE FEAR
← Back to All Lessons

📐 Lesson 4: Layout with Flexbox

⏱️ Estimated time: 30 minutes | Difficulty: Intermediate

Flexing Power

Flexbox (Flexible Box Layout) makes it easy to align and distribute space among items in a container, even when their size is unknown.

Flexbox = Flexible Box Layout

Flexbox makes centering, spacing, and aligning items incredibly easy.

.container {
    display: flex;             /* Enable flexbox */
    justify-content: center;   /* Horizontal alignment */
    align-items: center;       /* Vertical alignment */
    gap: 1rem;                 /* Space between items */
}

/* Perfect centering! */
.center-everything {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

justify-content (Main Axis)

justify-content: flex-start;     /* Left (default) */
justify-content: flex-end;       /* Right */
justify-content: center;         /* Center */
justify-content: space-between;  /* Even space, no edges */
justify-content: space-around;   /* Even space, half edges */
justify-content: space-evenly;   /* Equal space everywhere */

align-items (Cross Axis)

align-items: stretch;    /* Fill height (default) */
align-items: flex-start; /* Top */
align-items: flex-end;   /* Bottom */
align-items: center;     /* Center vertically */

flex-direction

flex-direction: row;            /* Left to right (default) */
flex-direction: row-reverse;    /* Right to left */
flex-direction: column;         /* Top to bottom */
flex-direction: column-reverse; /* Bottom to top */

flex-wrap & Child Properties

.container {
    flex-wrap: wrap;    /* Items wrap to next line */
}

.item {
    flex: 1;           /* Grow to fill space equally */
    flex: 2;           /* Takes 2x the space */
    flex-shrink: 0;    /* Don't shrink */
    align-self: flex-end; /* Override alignment */
    order: -1;         /* Move to first position */
}

Practical Example: Navigation Bar

nav {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem 2rem;
    background: #1a1a2e;
}

nav .logo { font-size: 1.5rem; font-weight: bold; }
nav .links { display: flex; gap: 2rem; }

✅ Quick Quiz

❓ How do you perfectly center content with flexbox?

❓ What does justify-content: space-between do?

❓ What does flex: 1 do on a child?

← Previous Next: Grid →