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

Display Flex – Creating a Flex Container

To create a flex container, set display: flex on a parent element. The parent becomes a block-level flex container, and its direct children become flex items arranged in a row by default. Use display: inline-flex when the container should behave like an inline-level box.

Display Flex – Creating a Flex Container

Quick Answer: To create a flex container, set display: flex on a parent element. The parent becomes a block-level flex container, and its direct children become flex items arranged in a row by default. Use display: inline-flex when the container should behave like an inline-level box.

S1. Why Do We Need a Flex Container?

Imagine you are building a navigation bar with three links: Home, Courses and Contact. You want the links to appear side by side with equal spacing.

Would you set a width and margin on every link? That works for three links, but every new link means more calculations.

CSS Flexbox solves this with one rule on the parent. Let's first see what happens without it.

S2. The Problem: Items Without a Flex Container

Block element = an element that starts on a new line and takes the full available width.

Imagine the three links are wrapped in div elements inside a navigation bar. No layout rule is applied to the parent.

Example 1: Navigation items without a flex container

This example renders, but the items do not sit side by side.

<!-- HTML -->
<nav class="menu">
    <div class="menu-item">Home</div>
    <div class="menu-item">Courses</div>
    <div class="menu-item">Contact</div>
</nav>

/* CSS */
.menu-item {
    padding: 12px 20px;
    background: #E2E8F0;
}

Expected output

[ Home                              ]
[ Courses                           ]
[ Contact                           ]

Each item is a block element, so each one takes its own line.

The page renders, but it is not the navigation bar we wanted. Block elements stack vertically by default.

What goes wrong?

  1. Stacked items: Each block element starts on a new line.
  2. Workarounds needed: Developers reach for floats, inline-block and manual widths.
  3. Risky changes: Adding a link can break a hand-calculated layout.
  4. Harder testing: Workarounds behave differently at different screen sizes.
  5. Poor clarity: The CSS does not say that the items belong in one row.

Now think about many menus, toolbars and card rows on one website. Repeating workarounds becomes harder to maintain.

Remember: The problem is not the items. The real problem is that the parent has no layout rule telling its children how to arrange themselves.

Animation 1: How a missing container creates workarounds

Three items, no layout rule on the parent

The red highlights show that every item needs its own workaround.

🏠HomeBlock elementNeeds float or width
📚CoursesBlock elementNeeds float or width
✉️ContactBlock elementNeeds float or width
 
.menu (normal block) No layout rule · items stack vertically
Missing container rule

The animation highlights the plain parent and the workarounds each item needs.

S3. The Solution: Turn the Parent into a Flex Container

Flexbox gives us a simpler design.

Flex container = a parent element with display: flex or display: inline-flex.

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

  • display: flex creates a block-level flex container.
  • display: inline-flex creates an inline-level flex container.
  • The direct children of the container become flex items.

Now the same three links sit side by side.

Example 2: A flex container for the navigation

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

.menu {
    display: flex;
}

.menu-item {
    padding: 12px 20px;
    background: #E2E8F0;
}

Expected output

[ Home ][ Courses ][ Contact ]

The three items sit in one row.

Notice the difference. The HTML stays the same, and one rule on the parent arranges every item.

Animation 2: The flex container design

One rule, one container

The parent controls the layout of its direct children.

🏠HomeFlex item
📚CoursesFlex item
✉️ContactFlex item
 
 
 
.menudisplay: flex
Direct childrenBecome flex items
Default rowMain axis is horizontal
Parent-controlled layout

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

Compare both approaches

Normal block layout compared with a flex container
Without a flex container With a flex container
Block children stack vertically. Children sit in a row by default.
Floats or manual widths are needed. One rule on the parent.
Adding an item may break the layout. Items share the available space.
Alignment needs separate hacks. Alignment properties are built in.
Layout intent is hidden. Layout intent is clear.

The idea to remember

  • Flex container = the parent element with display: flex or display: inline-flex.
  • Flex item = a direct child of the flex container.
  • display: flex = a block-level flex container.
  • display: inline-flex = an inline-level flex container.
  • Direct children only = deeper descendants do not become flex items.

S4. Step-by-Step Code Breakdown

1. Choose the parent element

Decide which element directly contains the items you want to arrange. In our example, it is nav.menu. This is the element that receives display: flex.

2. Apply display: flex

Add display: flex to the parent. The browser now treats it as a flex container, and each direct child becomes a flex item.

3. Understand the default behaviour

A new flex container already has useful defaults. You do not need to write them unless you want to change them.

Default values of a new flex container
Property Default Effect
flex-direction row Items are placed along a horizontal main axis.
flex-wrap nowrap Items stay on one line and may shrink.
justify-content normal (behaves like flex-start) Items start at the beginning of the main axis.
align-items normal (behaves like stretch) Items stretch across the cross axis when their cross size is auto.

4. Choose between flex and inline-flex

display: flex makes the container block-level, so it takes the full available width. display: inline-flex makes the container inline-level, so it sits inside a line of text and is only as wide as its content. Both arrange their children the same way.

Example 3: flex compared with inline-flex

<!-- HTML -->
<div class="box block-box">
    <span>A</span><span>B</span>
</div>

<div class="box inline-box">
    <span>A</span><span>B</span>
</div>

/* CSS */
.block-box  { display: flex; }         /* full width */
.inline-box { display: inline-flex; }  /* only as wide as its content */

Expected output

display: flex:
[ A  B ............................... ]   container fills the line

display: inline-flex:
[ A  B ]                                    container fits its content

5. Remember that only direct children become flex items

A flex container arranges its direct children only. Elements nested deeper stay in normal flow unless you make their parent a flex container too.

Example 4: Direct children and nested elements

<!-- HTML -->
<section class="cards">
    <div class="card">
        <h2>Web Development</h2>
        <p>Build modern websites.</p>
    </div>
    <div class="card">
        <h2>UI/UX Design</h2>
        <p>Create better experiences.</p>
    </div>
</section>

/* CSS */
.cards {
    display: flex;
    gap: 20px;
}

Expected output

[ Web Development      ]  [ UI/UX Design          ]
[ Build modern websites]  [ Create better          ]
                            experiences.

The two .card elements are flex items.
The h2 and p inside each card are not flex items of .cards.

This is still a clean design. If you also want the content inside a card arranged by Flexbox, add display: flex to that card as a separate container.

6. Add spacing with gap

Use gap on the container for consistent spacing between items. It does not add space around the outside edge of the container.

S5. Architecture and Real-World Trade-Offs

A flex container keeps layout rules in one place. It is useful in navigation bars, card rows, toolbars and form rows.

How the design fits a website

Imagine a website with a navigation bar, a card section and a search form. Each area has its own parent that acts as the flex container.

A focused container flow

Each website area uses its own parent as the flex container.

🧭Navigation barLinks in a row
🗂️Card sectionCards with spacing
🔍Search formInput and button together
 
 
 
.menudisplay: flex
.cardsdisplay: flex
.searchdisplay: inline-flex or flex

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 workarounds means fewer odd screen sizes to fix.
  • Flexibility: Adding or removing an item needs no recalculation.
  • Clear ownership: The container controls its direct children.
  • Built-in alignment: Alignment and spacing properties are ready to use.

Important trade-offs

  • Flexbox arranges direct children only, so nested layouts need nested containers.
  • Properties such as float and vertical-align have no effect on flex items.
  • Reordering items visually does not change the order of elements in the HTML.
  • Deeply nested flex containers can become hard to follow.

Important: Creating a flex container changes how its children are laid out, not how the container sits in the page. Use flex for a block-level container and inline-flex for an inline-level one.

S6. Common Mistakes and Best Practices

Mistake 1: Applying display: flex to the wrong element

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

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

Better: Apply display: flex to the parent that directly contains the items.

Rule: The container controls its direct children only.

Mistake 2: Expecting nested elements to become flex items

Wrong: Expect the heading and paragraph inside each card to line up in a row because the section is a flex container.

Why it fails: They are grandchildren of the container, so they stay in normal flow.

Better: Make each card its own flex container if its content needs Flexbox.

Rule: Every level of layout needs its own container.

Mistake 3: Using flex properties without display: flex

Wrong: Add justify-content or align-items to a normal block element.

Why it fails: These properties only affect flex containers, so they do nothing here.

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

Rule: Create the container before using any flex property.

Mistake 4: Using inline-flex when a full-width container is needed

Wrong: Use display: inline-flex for a navigation bar that should span the page.

Why it fails: The container shrinks to its content instead of filling the line.

Better: Use display: flex for full-width layouts.

Rule: Choose flex or inline-flex based on how the container itself should behave.

Mistake 5: Expecting float to work on flex items

Wrong: Keep float: left on items inside a flex container.

Why it fails: Floats are ignored on flex items, so old rules add confusion.

Better: Remove old float rules and let the container arrange the items.

Rule: Replace old layout hacks when you adopt Flexbox.

S7. How This Comes Up in Interviews

Question 1: What does display: flex do?

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

Strong answer:

"It turns the element into a block-level flex container. Its direct children become flex items, and they are laid out along the main axis, a row by default."

Question 2: What is the difference between display: flex and display: inline-flex?

Strong answer:

"Both create a flex container and arrange children the same way. flex makes the container block-level, so it takes the full available width. inline-flex makes it inline-level, so it sits in a line of text and fits its content."

Question 3: Which elements become flex items?

Strong answer:

"Only the direct children of the flex container. Deeper descendants stay in normal flow unless their own parent is also a flex container."

Question 4: What are the default values for a new flex container?

Strong answer:

"The direction is row, wrapping is nowrap, items start at the beginning of the main axis, and items stretch across the cross axis when their cross size is auto."

What should different experience levels explain?

  • Junior developer: Explain display: flex and show a simple row of items.
  • Senior developer: Explain direct children, defaults and the difference between flex and inline-flex.
  • Technical architect: Explain how container conventions keep layouts consistent across a design system.

S8. Hands-On Practice

Beginner: Create your first flex container

Create a parent with three child elements. Apply display: flex to the parent and observe the result.

Expected result: The three children sit in one row.

Intermediate: Compare flex and inline-flex

Create two containers with the same children. Use display: flex on one and display: inline-flex on the other. Add a background colour to each container.

Hint: Compare how wide each container is.

Advanced: Build nested containers

Create a row of three cards. Make the section a flex container, and make each card a flex container with a column direction for its heading and paragraph.

Expected result: The cards sit side by side, and the content inside each card is arranged by its own container.

S9. Next Steps and Community

Previous article: Introduction to CSS Flexbox.

Next article: Flex Direction – Row, Column and Reverse.

Continue the series by learning how flex-direction changes the main axis, and how row, row-reverse, column and column-reverse arrange the items inside your flex container.

Try the examples in your own HTML and CSS project. Change the number of items, switch between flex and inline-flex, try different flex directions, and share your layouts with the Upgradix community. Help other developers understand Flexbox through practical examples.

Create the container first. Then the items follow.

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.