DEV Community

Cover image for Flexbox Made Simple: Create Flexible Layouts with CSS
Kieren Quimsoquimos
Kieren Quimsoquimos

Posted on • Edited on

Flexbox Made Simple: Create Flexible Layouts with CSS

What is Flexbox?

Flexbox is a powerful CSS tool that makes creating responsive and flexible layouts easier than ever. It simplifies tasks like aligning elements, managing spacing, and adapting layouts for different screen sizes.

In this blog, we’ll cover the basics of Flexbox, explain how its properties work, and provide practical examples you can use in your projects. By the end, you’ll have the skills to create layouts that look great on any device. Let’s get started!

Flexbox vs. Grid vs. Float: A Simple Comparison

When creating layouts with CSS, there are several methods to choose from, each with its strengths. Let’s take a look at how Flexbox, Grid, and Float differ from each other.

Flexbox: Flexible and One-Dimensional

Flexbox is designed for one-dimensional layouts. It works best when you need to align elements in a row or a column, making it ideal for simpler layouts like navigation bars, centered content, or form elements.

Strengths:

  • Easy to use for alignment and distribution of space.
  • Great for responsive designs.
  • Handles dynamic content well.

When to Use:

  • For aligning and distributing elements in a single direction (row or column).
  • When you want elements to adjust automatically based on available space.

Grid: Powerful for Two-Dimensional Layouts

Grid is a more powerful layout tool that allows you to create both rows and columns. Unlike Flexbox, which handles only one dimension at a time, Grid is great for creating complex layouts like multi-column designs or entire page layouts.

Strengths:

  • Works in both rows and columns.
  • Great for complex layouts with multiple elements.
  • More control over placement and sizing of elements.

When to Use:

  • For creating complex page layouts, such as full-page grids or multi-column designs.
  • When you need precise control over both dimensions.

Float: Old School and Limited

Float was originally used for text wrapping and layout purposes, but it’s now considered outdated for general layout tasks. It can create layouts, but it often requires additional work to clear the float and manage spacing.

Strengths:

  • Simple to use for specific tasks like wrapping text around images.
  • Supported by all browsers.

When to Use:

  • For small layout tweaks, like wrapping text around images.
  • Not recommended for complex layouts or responsive designs.

Note:

  • Flexbox is ideal for simpler, one-dimensional layouts and offers a quick, flexible way to arrange items.
  • Grid is better for two-dimensional layouts, providing more control over complex designs
  • Float is outdated for modern layouts and should be avoided in favor of Flexbox or Grid.

Flexbox Basics: Key Properties and Axis Explained

To get started with Flexbox, it's essential to understand the core properties that define its behavior. Here, we’ll go over the most important Flexbox properties and explain how they work together to create flexible layouts.

1. display: flex

The display: flex property is the foundation of any Flexbox layout. By applying this property to a container, you turn it into a flex container, and its child elements become flex items. This enables you to use all the powerful alignment and layout properties that Flexbox offers.

  • How it works:
.container {
  display: flex;
}
Enter fullscreen mode Exit fullscreen mode
  • Effect: This makes the container a flex container, and all its direct children are now flex items that will follow Flexbox rules for alignment and distribution.

2. flex-direction

The flex-direction property defines the direction in which the flex items are arranged. It can be one of four values:

  • row (default): Items are arranged horizontally (left to right).
  • column: Items are arranged vertically (top to bottom).
  • row-reverse: Items are arranged horizontally but in reverse order.
  • column-reverse: Items are arranged vertically but in reverse order.

Example:

.container {
  display: flex;
  flex-direction: column;
}
Enter fullscreen mode Exit fullscreen mode

3. justify-content

The justify-content property aligns the flex items along the main axis (the direction set by flex-direction). It helps distribute the space between and around the items.

  • Values:
    • flex-start: Aligns items to the start of the container.
    • flex-end: Aligns items to the end of the container.
    • center: Aligns items in the center.
    • space-between: Distributes items with equal space between them.
    • space-around: Distributes items with equal space around them.

Example:

.container {
  display: flex;
  justify-content: center;
}
Enter fullscreen mode Exit fullscreen mode

4. align-items
The align-items property aligns flex items along the cross axis (perpendicular to the main axis). It controls the alignment of items vertically when the flex direction is row or horizontally when the direction is column.

  • Values:
    • flex-start: Aligns items to the start of the cross axis.
    • flex-end: Aligns items to the end of the cross axis.
    • center: Aligns items in the center of the cross axis.
    • stretch: Stretches items to fill the container (default behavior).
    • baseline: Aligns items along their baseline.

Example:

.container {
  display: flex;
  align-items: center;
}
Enter fullscreen mode Exit fullscreen mode

Understanding the Main Axis and Cross Axis

  • The main axis is the primary axis along which Flexbox arranges its items. It can be horizontal (row) or vertical (column), depending on the value of flex-direction.
  • The cross axis is perpendicular to the main axis. If the main axis is horizontal (row), the cross axis is vertical. If the main axis is vertical (column), the cross axis is horizontal.

When flex-direction: row, the main axis is horizontal, and the cross axis is vertical.

When flex-direction: column, the main axis is vertical, and the cross axis is horizontal.

Flexbox Examples: Simple Layouts You Can Create

Now that we’ve covered the basics of Flexbox, let’s look at some simple examples to see how it works in action.

1. Centering Elements
Flexbox makes centering elements both horizontally and vertically a breeze.

HTML:

<div class="container">
  <div class="box">Centered Content</div>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS:

.container {
  display: flex;
  justify-content: center;  /* Horizontally center */
  align-items: center;      /* Vertically center */
  height: 100vh;            /* Full viewport height */
}
Enter fullscreen mode Exit fullscreen mode

Result:

2. Creating a Simple Navigation Bar
Flexbox is great for creating horizontal navigation bars.

HTML:

<nav class="navbar">
  <a href="#">Home</a>
  <a href="#">About</a>
  <a href="#">Services</a>
  <a href="#">Contact</a>
</nav>
Enter fullscreen mode Exit fullscreen mode

CSS:

.navbar {
  display: flex;
  justify-content: space-around;  /* Evenly spaces the links */
  background-color: #333;
}

.navbar a {
  color: white;
  padding: 10px 20px;
  text-decoration: none;
}
Enter fullscreen mode Exit fullscreen mode

Result:

3. Building a Simple Responsive Grid
Flexbox can also be used to create simple responsive grids without needing media queries.

HTML:

<div class="grid">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS:

.grid {
  display: flex;
  flex-wrap: wrap;          /* Allows items to wrap to the next line */
}

.item {
  flex: 1 1 200px;         /* Items grow, shrink, and have a base size of 200px */
  margin: 10px;
  background-color: #f0f0f0;
  padding: 20px;
  text-align: center;
}
Enter fullscreen mode Exit fullscreen mode

Result:

These examples show just a few of the powerful layouts you can create with Flexbox. As you get more comfortable with it, you can combine these techniques to build more complex designs.

Advanced Flexbox Techniques: Nested Containers, Order, and Flex-Wrap

In this section, we'll explore some more advanced Flexbox features, such as nested containers, order, and flex-wrap. These techniques will give you more control over your layout and allow for complex designs.

1. Nested Flex Containers
Sometimes, you might need to create layouts within layouts. Flexbox allows you to nest flex containers inside each other for more control.

HTML:

<div class="outer-container">
  <div class="inner-container">
    <div class="item">1</div>
    <div class="item">2</div>
  </div>
  <div class="inner-container">
    <div class="item">3</div>
    <div class="item">4</div>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS:

.outer-container {
  display: flex;
  justify-content: space-between;
}

.inner-container {
  display: flex;
}

.item {
  margin: 10px;
  padding: 20px;
  background-color: #f0f0f0;
  text-align: center;
}
Enter fullscreen mode Exit fullscreen mode

Result:

In this example, the .outer-container is a flex container, and inside it, there are two nested .inner-container flex containers. This allows you to build more complex layouts within a main flex container.

2. Using order to Change Item Order
Flexbox allows you to control the order of items using the order property. By default, all items are ordered based on their HTML position. But with order, you can change the visual order without modifying the HTML.

HTML:

<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS:

.container {
  display: flex;
}

.item {
  margin: 10px;
  padding: 20px;
  background-color: #f0f0f0;
  text-align: center;
}

.item:nth-child(1) {
  order: 3;  /* Moves this item to the end */
}

.item:nth-child(2) {
  order: 1;  /* Moves this item to the beginning */
}

.item:nth-child(3) {
  order: 2;  /* This item is in the middle */
}
Enter fullscreen mode Exit fullscreen mode

Result:

In this example, we change the order of the items, even though their position in the HTML is 1-2-3. The order property allows you to visually rearrange the items.

3. Using flex-wrap to Allow Items to Wrap
The flex-wrap property allows flex items to wrap onto multiple lines when there’s not enough space. This is especially useful for responsive layouts where you want items to adjust to different screen sizes.

HTML:

<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS:

.container {
  display: flex;
  flex-wrap: wrap;  /* Allows items to wrap onto the next line */
  justify-content: space-between;
}

.item {
  flex: 1 1 200px;  /* Each item has a base size of 200px and can grow/shrink */
  margin: 10px;
  padding: 20px;
  background-color: #f0f0f0;
  text-align: center;
}
Enter fullscreen mode Exit fullscreen mode

Result:

In this example, the flex-wrap: wrap property allows the items to wrap to the next line if there’s not enough space, making it a great tool for creating responsive layouts.

Note:

  • Nested Flex Containers: Use Flexbox inside other Flex containers for more control over layout.
  • Order: Change the visual order of items without changing the HTML structure.
  • Flex-Wrap: Allow items to wrap onto new lines, useful for responsive layouts.

These advanced techniques give you even more flexibility and control when building layouts with Flexbox.

Common Mistakes with Flexbox and How to Avoid Them

Even though Flexbox is powerful, some common pitfalls can lead to unexpected results. Here are a few mistakes you might encounter and tips to avoid them:

1. Unintended Overflow

The Problem:
Flex items might overflow the container if their content doesn’t shrink as expected.

Example:

<div class="container">
  <div class="item">A very long text that doesn't wrap properly and causes overflow</div>
  <div class="item">Short</div>
</div>
Enter fullscreen mode Exit fullscreen mode
.container {
  display: flex;
}

.item {
  flex: 1;
}
Enter fullscreen mode Exit fullscreen mode

In this example, the long text pushes the layout out of the container.

The Fix:
Use the flex-shrink property or add overflow: hidden; or word-wrap: break-word;.

.item {
  flex-shrink: 1;           /* Allows items to shrink to fit */
  overflow: hidden;         /* Prevents content from spilling out */
  word-wrap: break-word;    /* Ensures long words break into the next line */
}
Enter fullscreen mode Exit fullscreen mode

2. Not Accounting for Default Margins

The Problem:
Browsers often apply default margins to elements like <p> or <h1>, which can disrupt Flexbox alignment.

Example:

<div class="container">
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
</div>
Enter fullscreen mode Exit fullscreen mode
.container {
  display: flex;
  justify-content: space-between;
}
Enter fullscreen mode Exit fullscreen mode

Default margins can cause uneven spacing, making the layout look unbalanced.

The Fix:
Reset margins with a CSS reset or explicitly set margins for your elements.

p {
  margin: 0;
}
Enter fullscreen mode Exit fullscreen mode

3. Using flex: 1 Without Understanding Its Behavior

The Problem:
Setting flex: 1 makes items grow and shrink equally, which can lead to unexpected results if one item’s content is significantly larger than others.

The Fix:
Fine-tune the flex property by specifying the grow, shrink, and basis values. For example:

.item {
  flex: 1 0 200px;  /* Grow, don’t shrink, and set a base size of 200px */
}
Enter fullscreen mode Exit fullscreen mode

4. Misunderstanding align-items and justify-content

The Problem:
Confusing align-items (controls the cross-axis) and justify-content (controls the main axis) can lead to layouts that don’t behave as expected.

The Fix:
Always remember:

  • justify-content: Horizontal alignment (main axis in row).
  • align-items: Vertical alignment (cross axis in row).

5. Forgetting flex-wrap for Responsive Layouts

The Problem:
By default, Flexbox doesn’t wrap items, which can cause them to shrink too much on smaller screens.

The Fix:
Add flex-wrap: wrap; to ensure items move to the next line when there’s not enough space.

.container {
  display: flex;
  flex-wrap: wrap;
}
Enter fullscreen mode Exit fullscreen mode

Note:
Avoiding these common mistakes will help you create layouts that are both flexible and visually appealing. Keep these tips in mind to make the most of Flexbox's powerful features!

Real-World Applications of Flexbox

Flexbox shines in scenarios where flexibility and responsiveness are essential. Here are some practical applications where Flexbox proves to be most beneficial:

1. Creating Responsive Layouts
Flexbox simplifies the process of designing layouts that adapt seamlessly to different screen sizes. Whether it's a mobile-first design or a desktop-centered layout, Flexbox makes alignment and spacing effortless.

  • Example: Building a product grid that adjusts from two columns on mobile to four columns on desktop by combining Flexbox with media queries.
.container {
  display: flex;
  flex-wrap: wrap;
}

.item {
  flex: 1 1 calc(50% - 10px); /* Two columns on smaller screens */
  margin: 5px;
}

@media (min-width: 768px) {
  .item {
    flex: 1 1 calc(25% - 10px); /* Four columns on larger screens */
  }
}
Enter fullscreen mode Exit fullscreen mode

2. Handling Dynamic Content
With Flexbox, you can easily manage layouts where the content size isn’t fixed. Items will automatically adjust to fit the space without breaking the design.

Example: Displaying a list of blog posts with varying titles and descriptions, ensuring they align evenly regardless of content length.

.container {
  display: flex;
  justify-content: space-between;
  align-items: stretch;
}
Enter fullscreen mode Exit fullscreen mode

3. Building Navigation Bars
Flexbox is ideal for creating navigation bars that are horizontally aligned and space elements evenly. You can even make the navigation adapt to smaller screens by wrapping items.

.navbar {
  display: flex;
  justify-content: space-between;
}
Enter fullscreen mode Exit fullscreen mode

4. Centering Content
Flexbox makes centering content on a page (both vertically and horizontally) effortless. This is particularly useful for splash screens, modals, or hero sections.

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

5. Creating Equal-Height Cards
In many designs, elements like cards need to have equal heights regardless of content length. Flexbox ensures consistent heights and alignment without additional hacks.

.container {
  display: flex;
  align-items: stretch;
}

.card {
  flex: 1;
  margin: 10px;
}
Enter fullscreen mode Exit fullscreen mode

Note:
Flexbox is a go-to solution for creating responsive and dynamic layouts, handling various content sizes, and simplifying alignment. Whether you're designing for mobile or desktop, Flexbox ensures your layouts are functional and visually appealing.

Visuals and Code

To make Flexbox concepts easier to understand, we’ll include diagrams, live code examples, and syntax-highlighted code snippets. Visual aids and interactive examples ensure you grasp the key ideas effectively.

1. Understanding Axes with Diagrams
Flexbox uses two axes:

  • Main Axis: The direction in which flex items are arranged.
  • Cross Axis: The perpendicular direction to the main axis.

Here’s a visual representation:
Image description

2. Interactive Examples

Example 1: Centering Items
This CodePen example shows how to center items both vertically and horizontally:

3. Illustrating Alignment with Syntax Highlighting

Example 2: Aligning Flex Items
Use the align-items property to control vertical alignment on the cross axis.

<div class="container">
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
</div>
Enter fullscreen mode Exit fullscreen mode
.container {
  display: flex;
  align-items: flex-start; /* Change this to center, flex-end, or stretch */
  height: 200px;
}

.item {
  padding: 10px;
  background: #28a745;
  color: white;
  margin: 5px;
}
Enter fullscreen mode Exit fullscreen mode

4. Live Demo for Nested Containers
Nested Flexbox containers can demonstrate advanced layouts. Check out this Codepen example:

Tips for Readers

  1. Experiment with the Code: Live examples are interactive—tweak properties to observe changes in real-time.
  2. Use Visual Tools: Websites like Flexbox Froggy provide a fun way to practice Flexbox concepts.
  3. Add Syntax Highlighting: Platforms like Dev.to and Markdown editors automatically format your code for better readability.

Note:
Visual aids, live examples, and syntax-highlighted snippets make learning Flexbox more interactive and engaging. Explore the provided links and diagrams to solidify your understanding.

Accessibility

Flexbox is not just a tool for creating visually appealing layouts; it also helps improve web accessibility when used correctly. Accessible layouts ensure that your website is usable by everyone, including people with disabilities.

How Flexbox Enhances Accessibility

1. Semantic HTML with Flexbox
Flexbox pairs well with semantic HTML elements like <header>, <nav>, <main>, and <footer>. Using these elements in combination with Flexbox improves the structure of your content for assistive technologies like screen readers.

<nav class="navbar">
  <a href="#home">Home</a>
  <a href="#about">About</a>
  <a href="#contact">Contact</a>
</nav>
Enter fullscreen mode Exit fullscreen mode
.navbar {
  display: flex;
  justify-content: space-around;
}
Enter fullscreen mode Exit fullscreen mode

2. Flexibility for Keyboard Navigation
Flexbox makes it easier to create keyboard-friendly layouts. For example, it simplifies arranging buttons and links in a way that ensures logical tab order.

Tip: Test navigation with the Tab key to ensure a smooth flow between focusable elements.

3. Adaptable Content for Screen Readers
Flexbox helps maintain a logical content order in the HTML source code while rearranging elements visually. This ensures screen readers can interpret the content in the intended order.

Avoid: Overusing the order property, as it may confuse users relying on assistive devices.

Best Practices for Accessible Flexbox Layouts

1. Preserve Logical HTML Order
Always structure your HTML in a logical reading order. Use Flexbox for visual adjustments rather than changing the content’s natural flow.

2. Use ARIA Landmarks When Necessary
Add ARIA roles (e.g., role="navigation") to clarify the purpose of elements for screen readers.

3. Test with Assistive Technologies
Use tools like screen readers (e.g., NVDA, VoiceOver) and accessibility checkers (e.g., Lighthouse or Axe) to verify your Flexbox layouts.

Provide Adequate Contrast and Focus Indicators
Flexbox often impacts the layout of buttons and links. Ensure they have enough contrast and are visibly focused when navigated with the keyboard.

button:focus, a:focus {
  outline: 2px solid #007bff;
  outline-offset: 2px;
}
Enter fullscreen mode Exit fullscreen mode

Note:
Flexbox can greatly contribute to accessible design when combined with semantic HTML and best practices. By testing your layouts with assistive tools and maintaining logical content order, you can create websites that are both flexible and inclusive.

Learning Flexbox

Flexbox is best learned through hands-on practice! Now that you’ve explored the basics, examples, and even advanced techniques, it’s time to put your knowledge into action.

Practice Ideas

1. Build a Layout from Scratch
Challenge yourself to design a simple webpage layout using Flexbox. For instance, create a responsive navigation bar, a photo gallery, or a centered card layout.

2. Modify the Blog’s Examples
Experiment with the code snippets provided in this blog. Adjust properties like justify-content, align-items, or flex-direction to see how they change the layout.

3. Play Flexbox Games
Use interactive tools like Flexbox Froggy to sharpen your skills in a fun and engaging way.

Put Your Knowledge to Use
Take what you’ve learned and start building! Whether it’s a small personal project or a layout tweak in an existing website, practicing Flexbox will solidify your skills.

Join the Conversation
Feel free to share your projects, ask questions, or drop your favorite Flexbox tips in the comments. Let’s grow and learn together!

Top comments (0)