LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
HTML & CSS

Creating Your First Flexbox Layout – Step-by-Step

To create a Flexbox layout, set display: flex on a parent container. Its direct children become flex items. You can then use properties such as gap, justify-content and align-items to arrange and align those items.

Creating Your First Flexbox Layout – Step-by-Step

Quick Answer: To create a Flexbox layout, set display: flex on a parent container. Its direct children become flex items. You can then use properties such as gap, justify-content and align-items to arrange and align those items.

S1. Why Do We Need Flexbox?

Imagine an educational website with three learning options: Web Development, UI/UX Design and Programming. We want to show them as three neat cards in one row.

Would you position every card by hand, calculating widths and margins for each screen size? That works for one screen, and breaks on the next.

CSS Flexbox solves this problem. Let's first see what happens without it.

S2. The Problem: Arranging Cards Without Flexbox

Flex container = a parent element that arranges its direct children as flex items.

Imagine the three cards are placed inside a section with no layout rules. Each card is a normal block element.

Example 1: Three cards without Flexbox

This example renders, but the cards do not sit in a row.

<!-- HTML -->
<section class="services">
    <div class="service-card">
        <h2>Web Development</h2>
        <p>Build modern websites.</p>
    </div>

    <div class="service-card">
        <h2>UI/UX Design</h2>
        <p>Create better user experiences.</p>
    </div>

    <div class="service-card">
        <h2>Programming</h2>
        <p>Learn programming concepts.</p>
    </div>
</section>

/* CSS */
.service-card {
    width: 30%;
    margin-right: 3%;
    padding: 24px;
}

Expected output

[ Web Development      ]
[ UI/UX Design         ]
[ Programming          ]

Cards stack vertically. Widths and margins are manual.

The cards are block elements, so each one starts on a new line. Setting widths does not put them in a row.

What goes wrong?

  1. Stacked cards: Block elements do not sit side by side by default.
  2. Manual widths: Percentages and margins must be calculated by hand.
  3. Risky changes: Adding a fourth card means recalculating every width.
  4. Harder testing: Each screen size needs its own checks and fixes.
  5. Poor clarity: The CSS does not say that the cards belong in one row.

Now think about ten sections and many different card counts. Hand-made widths become harder to maintain.

Remember: The problem is not the cards themselves. The real problem is placing every card by hand instead of letting the parent control the layout.

Animation 1: How manual layout creates extra work

Three cards, manual positioning

The red highlights show that every card needs its own width and margin.

💻Web DevelopmentNeeds widthNeeds margin
🎨UI/UX DesignNeeds widthNeeds margin
⌨️ProgrammingNeeds widthNeeds margin
 
Manual layout width: 30% · margin-right: 3% · repeated for every card
Manual workaround

The animation highlights the repeated manual rules each card needs.

S3. The Solution: Let the Parent Control the Layout

Flexbox gives us a simpler design.

Flex item = a direct child of a flex container.

Instead of styling every card, add one rule to the parent. The parent then arranges all of its direct children.

  • display: flex turns the parent into a flex container.
  • gap adds consistent spacing between the cards.
  • justify-content and align-items align the cards.

Now the same three cards sit neatly in one row.

Example 2: The parent controls the layout

Assumption: This example uses standard CSS supported by all modern browsers.

.services {
    display: flex;
    gap: 20px;
    justify-content: center;
    align-items: stretch;
}

Expected output

[ Web Development ] [ UI/UX Design ] [ Programming ]

Cards sit in one row with equal spacing.

Notice the difference. The HTML stays the same, and one parent rule now arranges every card.

Animation 2: The flex container design

One rule for the parent

Each card is arranged by the same flex container.

💻Card 1Web Development
🎨Card 2UI/UX Design
⌨️Card 3Programming
 
 
 
display: flexRow layout
gapEven spacing
justify-contentAlignment
Parent-controlled layout

The animation highlights each card and the container rules that arrange it.

Compare both approaches

Manual layout compared with Flexbox
Without Flexbox With Flexbox
Cards stack as block elements. Cards sit in a row by default.
Width and margin set on every card. One rule on the parent.
Adding a card means recalculating widths. Cards share the available space.
Spacing depends on separate margins. Spacing comes from gap.
Layout intent is hidden. Layout intent is clear.

The idea to remember

  • Flex container = the parent element with display: flex.
  • Flex item = a direct child of the flex container.
  • Main axis = the direction items are placed in, a row by default.
  • Cross axis = the direction perpendicular to the main axis.
  • Gap = consistent space between flex items.

S4. Step-by-Step Code Breakdown

1. Create the HTML structure

Create a parent section.services and place three div.service-card elements inside it. The parent becomes the flex container, and the cards become flex items.

Each card contains an h2 and a p. These do not become flex items of the outer container.

2. Activate Flexbox

Add display: flex to the parent. The cards now sit in a row because the default flex-direction is row.

3. Add spacing with gap

Use gap: 20px for consistent spacing between the cards. It is easier to maintain than separate margins, and it adds no space around the outside edge.

4. Align the cards

justify-content controls distribution along the main axis. align-items controls alignment along the cross axis.

How justify-content distributes flex items
Value Behaviour
flex-start Items start at the beginning of the main axis.
center Items are grouped at the centre.
flex-end Items move towards the end of the main axis.
space-between Space is distributed between items.
space-around Space is distributed around each item.
space-evenly Equal spacing is placed between items and container edges.

5. Make the layout responsive

Three cards may not fit in one row on a phone. Use flex-wrap: wrap to let items move onto another line, and flex: 1 1 220px to give each card a grow factor of 1, a shrink factor of 1 and a flex basis of 220px.

Example 3: Enable wrapping

.services {
    display: flex;
    gap: 20px;
    justify-content: center;
    flex-wrap: wrap;
}

.service-card {
    flex: 1 1 220px;
}

Expected output

Wide screen:    [ Card 1 ] [ Card 2 ] [ Card 3 ]
Narrow screen:  [ Card 1 ] [ Card 2 ]
                [ Card 3 ]

Cards wrap when the row runs out of space.

This is still a clean design. The parent decides how the cards grow, shrink and wrap.

Example 4: Complete HTML and CSS

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Flexbox Service Cards</title>

    <style>
        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            padding: 30px;
            font-family: Arial, sans-serif;
            background: #f1f5f9;
        }

        .services {
            display: flex;
            gap: 20px;
            justify-content: center;
            align-items: stretch;
            flex-wrap: wrap;
            max-width: 900px;
            margin: auto;
        }

        .service-card {
            flex: 1 1 220px;
            padding: 24px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }

        .service-card h2 {
            color: #4338ca;
            font-size: 20px;
        }

        .service-card p {
            color: #475569;
            line-height: 1.6;
        }
    </style>
</head>

<body>
    <section class="services">
        <div class="service-card">
            <h2>Web Development</h2>
            <p>Build modern websites.</p>
        </div>

        <div class="service-card">
            <h2>UI/UX Design</h2>
            <p>Create better user experiences.</p>
        </div>

        <div class="service-card">
            <h2>Programming</h2>
            <p>Learn programming concepts.</p>
        </div>
    </section>
</body>
</html>

Expected output

Web Development
Build modern websites.

UI/UX Design
Create better user experiences.

Programming
Learn programming concepts.

Layout: Flexible cards with consistent spacing.
Responsive behaviour: Cards can wrap onto new rows.

S5. Architecture and Real-World Trade-Offs

Flexbox helps keep layout rules in one place. It is useful in navigation bars, card lists, toolbars and form rows.

How the design fits a website

Imagine a learning website with a navigation bar, a service card section and a footer link row. Each area can use its own flex container.

A focused layout flow

Each website area has a parent that controls its own items.

🧭Navigation barLinks in a row
🗂️Service cardsCards with wrapping
🔗Footer linksSpaced items
 
 
 
.menuFlex container
.servicesFlex container
.footer-linksFlex container

The animation traces each website area to its own flex container.

Benefits for larger websites

  • Maintainability: Layout rules live on the parent, so changes happen in one place.
  • Testing: Fewer manual widths means fewer odd screen sizes to fix.
  • Flexibility: Adding or removing a card needs no recalculation.
  • Clear ownership: The container controls its direct children.
  • Consistent spacing: gap keeps spacing uniform.

Important trade-offs

  • Flexbox arranges items in one direction at a time.
  • Wrapped lines are sized independently, so the last row may look different.
  • Long text can force cards wider than expected, so check minimum widths.
  • Review layouts when the design or content changes.

Important: Wrapping depends on the container width and the items' sizing constraints. A narrow screen does not automatically guarantee a particular number of cards per row.

S6. Common Mistakes and Best Practices

Mistake 1: Forgetting display: flex

Wrong: Add justify-content without activating Flexbox on the parent.

Why it fails: Alignment properties only work on a flex container.

Better: Start with display: flex on the intended container.

Rule: Activate Flexbox before using any flex properties.

Mistake 2: Applying Flexbox to the wrong element

Wrong: Add display: flex to a single card when the goal is to arrange all cards together.

Why it fails: Only the direct children of that card become flex items.

Better: Apply Flexbox to the parent that directly contains the items.

Rule: The container controls its direct children only.

Mistake 3: Forgetting wrapping

Wrong: Leave the default flex-wrap: nowrap on a layout that needs multiple rows.

Why it fails: Items become crowded or overflow when a row has insufficient space.

Better: Use flex-wrap: wrap with a suitable flex basis.

Rule: Plan for small screens when building rows.

Mistake 4: Using margins for every spacing requirement

Wrong: Add separate margins to every card.

Why it fails: Spacing becomes inconsistent and hard to change.

Better: Use the container's gap property.

Rule: Control item spacing from the container.

Mistake 5: Skipping tests at different widths

Wrong: Check the layout only on one desktop screen.

Why it fails: Long text and small screens can cause overflow.

Better: Test at several viewport widths and with longer content.

Rule: Check minimum widths and content overflow before publishing.

S7. How This Comes Up in Interviews

Question 1: How do you create a Flexbox layout?

What the interviewer wants: They want to know whether you understand containers and items.

Strong answer:

"I set display: flex on the parent container. Its direct children become flex items. Then I use gap for spacing, justify-content for the main axis and align-items for the cross axis."

Question 2: What is the difference between justify-content and align-items?

Strong answer:

"justify-content distributes items along the main axis. align-items aligns them along the cross axis. In a default row layout, the main axis is horizontal and the cross axis is vertical."

Question 3: How do you make a flex layout responsive?

Strong answer:

"I use flex-wrap: wrap so items can move to a new line, and a flex basis such as flex: 1 1 220px so cards grow and shrink. Then I test at different viewport widths."

Question 4: Why use gap instead of margins?

Strong answer:

"gap creates consistent spacing between items from the container, and it adds no extra space around the outer edge. Separate margins are harder to keep consistent."

What should different experience levels explain?

  • Junior developer: Explain display: flex and show a simple row of cards.
  • Senior developer: Explain axes, wrapping behaviour and the flex shorthand.
  • Technical architect: Explain how layout conventions fit a design system and component library.

S8. Hands-On Practice

Beginner: Create three cards

Create a parent container with three cards. Apply display: flex and observe how the cards are arranged.

Expected result: The three cards sit in one row.

Intermediate: Change the alignment

Try justify-content: center, space-between and space-evenly. Observe how the available space changes.

Hint: justify-content works along the main axis.

Advanced: Build a responsive course section

Create four course cards. Use gap, flex-wrap and a suitable flex basis. Test the result on desktop and mobile screen widths.

Expected result: Your cards should form a flexible layout that adapts to the available space without unnecessary horizontal scrolling.

S9. Next Steps and Community

Previous article: Understanding the Main Axis and Cross Axis in Flexbox.

Next article: CSS Flexbox vs CSS Grid – Differences and When to Use Them.

Continue the series by comparing these two layout systems and learning when each one is the right choice.

Try the examples in your own HTML and CSS project. Change the number of cards, adjust the spacing and share your layouts with the Upgradix community. Help other developers understand Flexbox through practical examples.

Build one layout at a time, experiment with the properties, and understand how Flexbox responds.

Upgradix by Shrash Studio
Learn Technology. Build Your Future.
Quality Technology Education. Completely Free.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.