<28/>
28 Lazy Coder
CSS

CSS Flexbox: A Complete Beginner’s Guide with Examples

Featured Image
CSS Flexbox complete beginner's guide illustration with code editor
The Article
Table of Contents

If you have ever opened your CSS file and tried to line up three boxes side by side, only to watch them jump around, overlap, or refuse to sit in the middle of the page — don’t worry. Every single developer has been there. I remember spending almost two hours trying to center one <div> on a page before I finally understood what was going wrong.

The good news? There is one CSS tool that fixes almost all of these layout headaches in a few lines of code. It’s called Flexbox.

By the end of this article, you will not just know what Flexbox is — you will actually understand why it works the way it does, and you will be able to build real layouts with confidence.

Let’s start from zero.

What Is CSS Flexbox? (Explained Like You’re 5)

Think about a school assembly line. When the teacher tells students to “stand in one row, evenly spaced, all facing the same way” — every student automatically knows where to stand. Nobody needs a ruler. The row adjusts itself whether there are 10 students or 30 students.

That’s exactly what Flexbox does for boxes on a webpage.

Flexbox (Flexible Box Layout) is a CSS layout system that helps you arrange elements in a row or a column, and automatically handles spacing, alignment, and sizing — even when the screen size changes.

Before Flexbox existed, developers used tricks like float, display: inline-block, or even HTML tables just to place three boxes side by side. These tricks were unreliable. Boxes would break on smaller screens, spacing would go wrong, and centering something vertically felt like solving a puzzle.

Flexbox was built to solve exactly this problem.

Did You Know? Flexbox became a stable part of the CSS specification around 2015–2017, and today it is supported by every modern browser. You can safely use it in any project.

Why Do We Need Flexbox? What Problem Does It Solve?

Let’s answer this directly, the way we should after every new concept.

Why do we need this? Because websites are not built with fixed-size boxes anymore. A visitor might open your site on a mobile phone, a tablet, or a large monitor. Your layout needs to adjust automatically — and doing that with old CSS methods was painful.

What problem does it solve? Flexbox solves three big layout problems in one shot:

  1. Arranging items in a row or column easily.
  2. Aligning items — center, left, right, top, bottom — without guesswork.
  3. Distributing empty space between items automatically.

What happens if we don’t use it? You would have to manually calculate widths, use extra wrapper <div>s, and write messy CSS with float and clear — and it would still break on different screen sizes.

Think of Flexbox like a smart TV remote. Without it, you’d be getting up from the couch and manually adjusting the TV’s antenna every time (old CSS methods). With the remote (Flexbox), one press does everything (auto align, auto space, auto adjust).

Flex Container vs Flex Items — The Foundation of Flexbox

This is the single most important idea in this entire article. Once this clicks, everything else becomes easy.

Imagine a school classroom:

In CSS, it works the same way:

Syntax: Creating a Flex Container

css

.container {
  display: flex;
}

Explaining every line:

That’s it. One line of CSS, and suddenly all the child elements inside .container line up in a row automatically.

Example: HTML + CSS

html

<div class="container">
  <div class="box">1</div>
  <div class="box">2</div>
  <div class="box">3</div>
</div>

css

.container {
  display: flex;
  background-color: #F7F3E9;
  padding: 20px;
}

.box {
  background-color: #FF7A18;
  color: white;
  padding: 20px;
  margin: 5px;
}

Output: The three boxes (1, 2, 3), which would normally stack on top of each other like a to-do list, now sit neatly side by side in a single row.

Why does this output appear? Because display: flex changes the default behavior of the container. Normally, <div> elements stack vertically (like items in a shopping list). But once the container becomes a flex container, its children line up horizontally by default, in a row, side by side — just like students standing in a line.

Real-world use case: This exact pattern is used in navigation bars. Think of any website’s top menu — Home, About, Services, Contact — all sitting neatly in a single row. That’s Flexbox at work.

[Diagram: Flex container and flex items arranged in a row]

The Two Axes of Flexbox: Main Axis and Cross Axis

This concept confuses most beginners — but once you understand it with an example, you’ll never forget it.

Imagine a traffic signal road. Cars can move in two directions:

In Flexbox:

Why does this matter? Because two of the most important Flexbox properties — justify-content and align-items — work based on these axes:

PropertyWorks AlongPurpose
justify-contentMain AxisAligns items horizontally (in default row direction)
align-itemsCross AxisAligns items vertically (in default row direction)

Tip: If justify-content isn’t doing what you expect, check your flex-direction first. The “main axis” changes when you switch from row to column.

flex-direction: Choosing Row or Column

Let’s go back to real life. Think about YouTube’s homepage. Video thumbnails are arranged in a row across the screen. Now think about WhatsApp’s chat list — messages are stacked one below another, in a column.

Both layouts are possible with Flexbox, just by changing one property: flex-direction.

Syntax

css

.container {
  display: flex;
  flex-direction: row; /* default */
}

css

.container {
  display: flex;
  flex-direction: column;
}

Explaining the values:

ValueWhat It Does
rowItems arranged left to right (default)
row-reverseItems arranged right to left
columnItems arranged top to bottom
column-reverseItems arranged bottom to top

Output for column: Instead of boxes 1, 2, 3 sitting side by side, they now stack on top of each other — like a vertical list.

Real-world use case: Mobile app menus, WhatsApp chat lists, and sidebar navigation menus almost always use flex-direction: column.

justify-content: Controlling Horizontal Spacing (Main Axis)

Imagine a movie theatre row of seats. Sometimes the seats are:

justify-content controls exactly this kind of spacing — but for your flex items, along the main axis.

Syntax and Values

css

.container {
  display: flex;
  justify-content: center;
}
ValueWhat Happens
flex-startItems stick to the start (default)
flex-endItems stick to the end
centerItems are centered
space-betweenEqual space between items, none on the edges
space-aroundEqual space around each item
space-evenlyCompletely equal space everywhere, including edges

Explaining space-between vs space-around:

Think about three friends sharing a WhatsApp group photo layout:

Common Mistake: Beginners often confuse space-between and space-around. Remember: “between” means space is only between items, not on the outer edges.

align-items: Controlling Vertical Alignment (Cross Axis)

Now think about an ATM machine screen. The buttons on the side are aligned vertically — some ATMs align them to the top, some to the center of the screen height.

align-items controls how flex items align along the cross axis (vertical, by default).

Syntax and Values

css

.container {
  display: flex;
  align-items: center;
}
ValueWhat Happens
stretchItems stretch to fill the container height (default)
flex-startItems align to the top
flex-endItems align to the bottom
centerItems are vertically centered
baselineItems align based on their text baseline

The Famous Centering Trick

This is probably the most searched CSS question ever: “How do I center a div?”

css

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

Explaining every line:

Output: Any element inside .container — a login box, a card, a button — sits perfectly in the middle of the screen, both horizontally and vertically.

Real-world use case: This exact pattern is used on login pages, “404 Page Not Found” pages, and loading screens across almost every modern website.

Best Practice: Whenever you need to center something perfectly on a page, reach for justify-content: center + align-items: center before trying anything else. It works in 90% of real cases.

flex-wrap: What Happens When Items Don’t Fit?

Picture a shopping mall parking lot. If ten cars try to fit into a five-car row, either the cars overflow the lane, or the parking system creates a new row for the extra cars.

By default, Flexbox tries to squeeze all items into a single line — even if they shrink uncomfortably. flex-wrap lets items move to a new line instead.

Syntax

css

.container {
  display: flex;
  flex-wrap: wrap;
}
ValueMeaning
nowrapAll items stay in one line (default), shrinking if needed
wrapItems move to a new line when there isn’t enough space
wrap-reverseSame as wrap, but new lines are added above instead of below

Real-world use case: Online shopping websites (like product cards on an e-commerce page) use flex-wrap: wrap so that product cards automatically rearrange into new rows on smaller screens like mobile phones.

Warning: If you forget flex-wrap, your layout may look fine on a laptop but completely break — items squished or overflowing — on a mobile phone. Always test responsiveness.

flex-grow, flex-shrink, and flex-basis: Controlling Item Size

Here’s where a lot of beginners get scared by the terminology — but the real-life example makes it simple.

Think about splitting a food order bill among friends:

flex-grow

css

.box1 { flex-grow: 1; }
.box2 { flex-grow: 2; }

Explanation: If there is extra empty space in the container, .box2 will grow to take up twice as much of that extra space compared to .box1, because its flex-grow value is twice as large. If flex-grow is 0 (the default), the item won’t grow at all, even if there’s space.

flex-shrink

css

.box1 { flex-shrink: 1; }
.box2 { flex-shrink: 0; }

Explanation: If the container is too small to fit all items, .box1 is allowed to shrink, but .box2 (with flex-shrink: 0) refuses to shrink and keeps its original size — even if that causes overflow.

flex-basis

css

.box {
  flex-basis: 200px;
}

Explanation: This sets the “starting size” of the flex item before any growing or shrinking happens — similar to width, but it specifically works within the flex layout system.

The Shortcut: flex

In real projects, developers usually combine all three using the shorthand flex property:

css

.box {
  flex: 1 1 200px;
}

This means: flex-grow: 1, flex-shrink: 1, flex-basis: 200px — grow if there’s space, shrink if needed, but start at 200px.

Interview Tip: A common interview question is: “What is the difference between flex-basis and width?” The answer: flex-basis is flex-aware and takes priority over width inside a flex container, while width is a general-purpose CSS property used everywhere.

align-self: Overriding Alignment for One Item

Sometimes, in a WhatsApp group photo, everyone stands at the same height — except one taller friend at the back who is positioned slightly differently on purpose. That’s exactly what align-self allows.

css

.special-box {
  align-self: flex-end;
}

Explanation: While align-items sets alignment for all items in the container, align-self lets you override that alignment for just one specific item — without touching the others.

Real-world use case: A “Featured” product card in an e-commerce grid that needs to align differently from the rest.

gap: Adding Space Between Items (Without Margin Hacks)

Before gap existed, developers used margin on flex items to create spacing — but this often caused extra, unwanted space at the very edges of the container.

css

.container {
  display: flex;
  gap: 20px;
}

Explanation: gap adds consistent spacing between flex items only — not on the outer edges of the container. This is cleaner and far easier to manage than manually adding margins to every item.

Best Practice: Always prefer gap over margin-based spacing tricks when working with modern Flexbox layouts. It is supported in all current browsers.

Real-World Example: Building a Simple Navigation Bar

Let’s put everything together into something practical — a navigation bar, just like the one at the top of almost every website you visit, including this one.

html

<nav class="navbar">
  <div class="logo">28LazyCoder</div>
  <ul class="nav-links">
    <li>Home</li>
    <li>Blog</li>
    <li>About</li>
    <li>Contact</li>
  </ul>
</nav>

css

.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #202020;
  padding: 15px 30px;
}

.logo {
  color: #FF7A18;
  font-weight: bold;
}

.nav-links {
  display: flex;
  gap: 25px;
  list-style: none;
  color: white;
}

Explaining every line:

Output: A clean, professional navigation bar with the logo on the left and the menu items neatly spaced on the right — exactly like what you’d see on most real websites.

Why does this matter? Because this single pattern — container + justify-content: space-between + align-items: center — is one of the most reused layout patterns in real-world frontend development.

[Screenshot: Example navbar layout using Flexbox]

Flexbox vs CSS Grid: What’s the Difference?

Beginners often ask: “If Flexbox can do all this, why does CSS Grid exist?” Great question — and it deserves a clear answer.

FeatureFlexboxCSS Grid
Layout DirectionOne dimension (row OR column)Two dimensions (rows AND columns together)
Best ForNavigation bars, buttons, aligning small groups of itemsFull page layouts, complex grids like photo galleries
Learning CurveEasier for beginnersSlightly more advanced
Common Use CaseAligning items within a sectionStructuring the entire page layout

Simple rule of thumb: If you’re arranging items in a single row or column, use Flexbox. If you’re designing a full layout with both rows and columns working together (like a dashboard), CSS Grid is usually the better tool. In many real projects, developers use both together.

Common Mistakes Beginners Make with Flexbox

Common Mistake #1: Forgetting that display: flex must be applied to the parent, not the child. Beginners often mistakenly add display: flex to the item they want to move, instead of its container.

Common Mistake #2: Confusing justify-content and align-items. Remember: justify-content = main axis (horizontal by default), align-items = cross axis (vertical by default).

Common Mistake #3: Not adding flex-wrap: wrap, causing items to awkwardly shrink or overflow on smaller screens.

Common Mistake #4: Using margin for spacing between items instead of the simpler and cleaner gap property.

Best Practices for Using Flexbox in Real Projects

Interview Questions on Flexbox (For Beginners)

  1. What is the difference between a flex container and a flex item?
  2. What is the default value of flex-direction?
  3. What is the difference between justify-content and align-items?
  4. How do you vertically and horizontally center a <div> using Flexbox?
  5. What is the difference between space-between and space-around?
  6. What does the flex-grow property do?
  7. When would you choose CSS Grid over Flexbox?

Interview Tip: Interviewers often ask you to center a div live on a whiteboard or code editor. Practice the justify-content: center + align-items: center pattern until it becomes muscle memory.

Frequently Asked Questions (FAQs)

Q1. Is Flexbox still relevant in 2026, or has CSS Grid replaced it? Flexbox is still very much relevant. It is not replaced by CSS Grid — both exist for different purposes. Flexbox is ideal for one-dimensional layouts (a single row or column), while Grid handles two-dimensional layouts. Most real projects use both together.

Q2. Do I need to learn CSS Grid before Flexbox? No. Flexbox is generally considered easier to learn first, and it’s used far more frequently for smaller components like navbars, buttons, and cards. Learn Flexbox first, then move on to Grid.

Q3. Does Flexbox work on all browsers? Yes. Flexbox is supported by all modern browsers, including Chrome, Firefox, Safari, and Edge. It has been a stable part of the CSS specification for many years now.

Q4. Can I use Flexbox for the entire page layout? You can, especially for simpler websites. But for complex layouts involving both rows and columns interacting together (like a dashboard), CSS Grid is usually a better fit.

Q5. What is the difference between flex-basis and width? flex-basis defines the starting size of an item specifically within a flex container and takes priority over width when both are set on a flex item. width is a general CSS property used in all types of layouts.

Conclusion

Flexbox might feel a little overwhelming with all its property names at first — justify-content, align-items, flex-grow, flex-wrap — but once you understand the core idea of a flex container and its flex items, everything else is just fine-tuning.

Start small. Practice centering a single box. Then build a simple navbar. Then try a row of cards that wraps on mobile. Each small project will make these properties feel natural, until one day you’ll write display: flex without even thinking about it — the same way you don’t think twice before opening WhatsApp to send a message.

You don’t need to memorize everything today. Bookmark this guide, come back to it, and practice a little every day. That’s exactly how real developers learn.

Additional SEO & Technical Assets

Internal Linking Table

Anchor TextTarget URL
JavaScript Arrayshttps://28lazycoder.com/javascript-arrays/
JavaScript Functions Explained for Beginnershttps://28lazycoder.com/javascript-functions/
JavaScript Conditional Statements Guidehttps://28lazycoder.com/javascript-conditional-statements/
Custom WordPress Theme Development Guidehttps://28lazycoder.com/custom-wordpress-theme-development/

External Linking Table (Trusted Sources)

TitleTarget URLContext
MDN Flexbox documentationhttps://developer.mozilla.org/en-US/docs/Web/CSS/CSS_flexible_box_layoutReference for further reading
W3C Flexbox specificationhttps://www.w3.org/TR/css-flexbox-1/Technical spec reference
web.dev Flexbox guidehttps://web.dev/learn/css/flexbox/Deeper learning resource
AR

Ashutosh Rajbhar

Full-stack developer

3+ years building WordPress, React, and performance-focused web projects.

Related Articles
Previous ← JavaScript Data Types: A Complete Beginner’s Guide with Examples