How To Build A Basic Flexbox Layout: A Tutorial With Examples

Master CSS Flexbox from fundamentals to advanced layouts with practical examples and code samples you can use today

CSS Flexbox revolutionized how we create web layouts. Before Flexbox, developers relied on floats, positioning, and table-based layouts--approaches that required workarounds and often produced fragile code. Flexbox provides a clean, one-dimensional layout system that simplifies complex arrangements and makes responsive design more intuitive.

This tutorial walks you through everything you need to master flexbox layouts, from basic concepts to practical implementations you can use in your projects today. Whether you're building responsive navigation menus or card-based content grids, Flexbox is an essential tool in your CSS toolkit. Before diving into Flexbox, make sure you're comfortable with CSS fundamentals to get the most out of these layout techniques.

What Is Flexbox and Why Should You Use It?

Flexbox, short for "Flexible Box Layout," is a CSS layout model that enables you to arrange elements in a flexible way within a container. Unlike earlier layout methods that required hacks and workarounds, Flexbox provides a straightforward system for aligning items and distributing space dynamically.

Key advantages of Flexbox:

  • Simplified centering: Centering elements both horizontally and vertically, once considered one of CSS's hardest problems, becomes trivial with Flexbox
  • Responsive layouts without media queries: Flex items can grow and shrink to fill available space, reducing the need for complex breakpoint-based styling
  • Reorder elements without HTML changes: The order property allows visual reordering without modifying source HTML
  • Equal-height columns made easy: By default, flex items stretch to fill the container's cross size
  • Content-aware spacing: Space distribution properties handle spacing intelligently based on content size

According to the MDN Web Docs, Flexbox was designed to address the limitations of traditional layout methods and provide a more efficient way to arrange, align, and distribute space among items in a container.

Understanding the Two-Axis Model

Every flex container operates along two perpendicular axes--the main axis and the cross axis. Understanding these axes is essential to using Flexbox effectively.

The main axis is the primary direction along which flex items are laid out. This axis can be horizontal (left to right or right to left) or vertical (top to bottom or bottom to top), depending on the flex-direction property. Items flow along this axis from main-start to main-end.

The cross axis runs perpendicular to the main axis. When items are arranged in a row (horizontal main axis), the cross axis is vertical. When items are arranged in a column (vertical main axis), the cross axis is horizontal.

Visualize a coordinate system where the main axis is horizontal and runs left to right. At the leftmost point is main-start, and at the rightmost point is main-end. The cross axis runs vertically through the center of the container, with cross-start at the top and cross-end at the bottom. All justify-content properties work along the main axis, while align-items properties work along the cross axis. As explained in the freeCodeCamp Flexbox Handbook, this two-axis model gives you precise control over how elements are positioned and spaced within your layouts.

Flex Containers and Flex Items

To use Flexbox, you designate a container element as the flex context by applying display: flex or display: inline-flex. This simple declaration transforms all direct children into flex items that can be manipulated with flexbox properties.

Creating a Flex Container:

.container {
 display: flex; /* or display: inline-flex; */
}

The display: flex value makes the container behave like a block-level element--it takes up the full available width and starts on a new line. The display: inline-flex value makes the container behave like an inline-level element, allowing it to flow alongside other inline content. This distinction is important when building complex responsive layouts that integrate with other page elements.

What Becomes a Flex Item?

Only direct children of a flex container become flex items. Descendants nested deeper in the HTML hierarchy are not affected by the flex context unless they themselves become flex containers.

<section class="container">
 <div>Flex Item 1</div> <!-- This is a flex item -->
 <div>Flex Item 2</div> <!-- This is a flex item -->
 <div>
 <p>Not a flex item</p> <!-- This paragraph is NOT a flex item -->
 </div>
</section>

As documented by MDN Web Docs, this parent-child relationship is fundamental to how Flexbox works--only the immediate children gain flex properties, creating a predictable and manageable layout system.

Flex Container Properties

flex-direction values
1.container {2 flex-direction: row | row-reverse | column | column-reverse;3}

flex-direction: Setting the Main Axis Direction

The flex-direction property establishes the main axis, determining the direction flex items flow within the container.

  • row (default): Items flow left to right in horizontal rows
  • row-reverse: Items flow right to left, reversing the visual order
  • column: Items flow top to bottom in vertical columns
  • column-reverse: Items flow bottom to top, reversing visual order

⚠️ Accessibility note: The reverse values only affect visual presentation, not the underlying HTML order. Screen readers and keyboard navigation follow the HTML source order, not the visual order created by flexbox. The freeCodeCamp Flexbox Handbook emphasizes this important consideration for accessible web design.

flex-wrap values
1.container {2 flex-wrap: nowrap | wrap | wrap-reverse;3}

flex-wrap: Controlling Item Wrapping

By default, flex items will shrink to fit their container rather than wrap to a new line. The flex-wrap property controls whether items wrap or overflow.

  • nowrap (default): All items stay on a single line, shrinking as needed to fit
  • wrap: Items wrap onto multiple lines from top to bottom
  • wrap-reverse: Items wrap onto multiple lines but from bottom to top
justify-content values
1.container {2 justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly;3}

justify-content: Aligning Along the Main Axis

The justify-content property distributes space along the main axis and controls how items are aligned at the start, end, or center of the container.

  • flex-start (default): Items packed toward the start of the main axis
  • flex-end: Items packed toward the end of the main axis
  • center: Items centered along the main axis
  • space-between: First item at start, last item at end, equal space between items
  • space-around: Equal space around each item (half-size gaps at start and end)
  • space-evenly: Truly equal space between all items including edges

This property is essential for building navigation bars and distributing content evenly across your layouts.

align-items values
1.container {2 align-items: stretch | flex-start | flex-end | center | baseline;3}

align-items: Aligning Along the Cross Axis

The align-items property distributes space along the cross axis, aligning items relative to each other within the container.

  • stretch (default): Items stretch to fill the container's cross size
  • flex-start: Items aligned at the start of the cross axis
  • flex-end: Items aligned at the end of the cross axis
  • center: Items centered along the cross axis
  • baseline: Items aligned along their text baseline, even with different font sizes

💡 Tip: Use align-items: center combined with justify-content: center to perfectly center any element within its container. This combination solves the classic CSS centering challenge that developers have struggled with for years, as noted in the freeCodeCamp Flexbox Handbook.

gap property examples
1.container {2 gap: 10px; /* Same gap for rows and columns */3 gap: 20px 10px; /* row-gap column-gap */4 row-gap: 20px; /* Space between rows only */5 column-gap: 10px; /* Space between columns only */6}

The gap Property: Spacing Between Items

The gap property provides a clean way to add space between flex items without using margins. Gap is preferred over margins for flexbox layouts because it only creates space between items, not outside the container, eliminating the need for margin adjustments on first and last items. This makes your CSS more maintainable and reduces the need for complex selectors to target specific items. For more spacing techniques, check out our guide on CSS word-wrap and spacing.

Flex Item Properties

order property
1.item {2 order: 5; /* Higher values appear later, lower values appear earlier */3}

order: Controlling Visual Order

The order property controls the visual order of flex items without changing the HTML structure. By default, items appear in their source order with an implicit order value of 0. Items with the same order value maintain their source order.

⚠️ Accessibility warning: Like reverse flex-direction values, the order property only affects visual presentation. Screen readers and keyboard navigation follow HTML source order. This is particularly important when building accessible web applications that work for all users.

align-self values
1.item {2 align-self: auto | flex-start | flex-end | center | stretch | baseline;3}

align-self: Individual Cross-Axis Alignment

The align-self property allows individual flex items to have different cross-axis alignment than the container's align-items setting. The auto value inherits the align-items value from the flex container, providing flexibility while maintaining a sensible default.

flex shorthand examples
1.item {2 flex: 1 1 200px; /* grow shrink basis */3 flex: 1 200px; /* grow (shrink defaults to 1) */4 flex: 200px; /* grow defaults to 1, shrink defaults to 1 */5 flex: 1; /* shorthand for 1 1 0% */6}

flex-grow, flex-shrink, and flex-basis

These three properties control how flex items size themselves:

  • flex-grow: Specifies how much an item should grow relative to other items when there is extra space. A value of 0 (default) means the item won't grow.

  • flex-shrink: Specifies how much an item should shrink when there is insufficient space. A value of 0 prevents shrinking.

  • flex-basis: Specifies the initial main size of a flex item before growing or shrinking occurs.

The recommended pattern is to use the flex shorthand rather than individual properties, as it handles edge cases better and provides more predictable behavior. As documented by MDN Web Docs, this shorthand is the preferred approach for modern flexbox development.

Practical Layout Examples

Perfect centering with Flexbox
1.center-box {2 display: flex;3 justify-content: center;4 align-items: center;5 height: 200px;6}

Perfect Centering

The classic "holy grail of CSS" solved with just two lines. This combination centers child elements perfectly both horizontally and vertically. This technique is invaluable for creating landing page hero sections and modal dialogs.

Responsive card grid layout
1.card-grid {2 display: flex;3 flex-wrap: wrap;4 gap: 1.5rem;5}6 7.card {8 flex: 1 1 300px; /* Grow, shrink, minimum 300px width */9}

Responsive Card Grid

Create responsive card layouts that wrap automatically and maintain equal minimum widths. The flex: 1 1 300px shorthand means each card will grow to fill space, shrink if needed, but won't go below 300px width. This pattern is perfect for portfolio showcases, feature grids, and content cards.

Equal-height sidebar layout
1.layout {2 display: flex;3}4 5.sidebar {6 flex: 0 0 250px; /* Fixed width sidebar */7}8 9.content {10 flex: 1; /* Takes remaining space */11}

Equal-Height Sidebar Layout

A common two-column layout pattern with a fixed-width sidebar and content area that takes the remaining space. Flexbox makes both columns equal height automatically--a task that previously required complex hacks or JavaScript. This pattern is ideal for blog layouts, documentation sites, and e-commerce product pages.

When to Use Flexbox

Best practices for choosing Flexbox vs other layout methods

Single-Dimensional Layouts

Perfect for layouts in one direction--either rows OR columns, but not both simultaneously

Vertical Centering

The go-to solution for centering content both horizontally and vertically

Navigation Menus

Ideal for navigation bars and toolbars with aligned items

Card Layouts

Creates equal-height columns and responsive card grids with minimal code

Form Layouts

Aligns inputs and labels cleanly without complex positioning

Sticky Footers

Keeps footers at the bottom when page content is short

Best Practices for Flexbox

  1. Start with display: flex on your container to activate the flex context
  2. Use flex-flow to combine direction and wrapping in a single declaration
  3. Prefer gap over margins for spacing between items--it handles edge cases automatically
  4. Use the flex shorthand instead of individual properties for better behavior
  5. Consider accessibility when using order or reverse values--screen readers follow HTML order
  6. Test with real content to see how flex items behave with varying content sizes

Following these practices will help you write cleaner, more maintainable CSS and avoid common pitfalls when building responsive websites.

Flexbox and SEO-Friendly Web Design

While Flexbox is primarily a layout tool, how you structure your layouts can impact your site's SEO performance. Search engines value fast-loading, mobile-friendly websites with clean code. Flexbox helps achieve both by reducing the need for layout hacks and enabling responsive designs that work across devices.

When implementing Flexbox layouts, keep these SEO considerations in mind:

  • Semantic HTML: Ensure your flex containers use proper semantic tags rather than generic divs where appropriate
  • Content order: Remember that screen readers follow HTML order, not visual order created by Flexbox--keep important content early in your HTML
  • Performance: Flexbox is well-supported and performant, but avoid over-nesting containers as this can increase DOM depth

For comprehensive SEO optimization of your website, our SEO services can help improve your search rankings while maintaining excellent user experience.

Summary

Flexbox provides a powerful, intuitive system for creating one-dimensional layouts. By understanding the two-axis model and mastering both container and item properties, you can create responsive, flexible layouts with less code and fewer headaches. The key to mastery is practice--experiment with different property combinations and build real layouts to solidify your understanding.

Whether you're building custom web applications, responsive e-commerce sites, or interactive landing pages, Flexbox is an essential tool that will improve your development workflow and the quality of your output. Start with simple layouts and gradually tackle more complex designs as you become comfortable with the fundamentals.

Ready to Build Modern Web Layouts?

Our team of experienced developers can help you create responsive, flexible web designs that work across all devices.