Getting Started with CSS Flexbox: The Ultimate Beginner’s Handbook

Meyoron Aghogho
10 min readNov 13, 2024

--

Creating responsive and flexible layouts is a key part of modern web design. While older methods like floats and tables used to dominate, they often required complex workarounds. Enter CSS Flexbox — a powerful layout tool that simplifies alignment and distribution of space among items within a container.

What is Flexbox?

It stands for “Flexible Box Layout” and offers a simpler way to arrange elements in rows or columns. Flexbox adjusts items dynamically based on available space, making it perfect for responsive design.

Why Learn Flexbox?

  1. Built for Responsiveness: Automatically adjusts to different screen sizes, ideal for mobile-first design.
  2. Simpler Code: Reduces the need for complex CSS, making your code cleaner.
  3. Better Alignment Control: Easily centres items or aligns them to edges.
  4. Versatile: Perfect for building navigation bars, grids, and adaptive layouts.

This guide covers everything you need to start using Flexbox effectively. Let’s dive in!

Core Concepts of Flexbox

Before diving into the practical aspects of Flexbox, it’s crucial to understand its core concepts. At its foundation, Flexbox is designed to control the alignment, spacing, and order of items within a flex container.

1. The Flex Container and Flex Items

  • Flex Container: The parent element that uses display: flex; to activate Flexbox. All its direct children automatically become flex items.
  • Flex Items: The child elements inside the flex container that respond to Flexbox properties.

Example:

<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
.container {
display: flex;
}

Here, .container is the flex container, and the three <div> elements are the flex items.

2. The Flex Axis

Flexbox operates along two main axes:

  • Main Axis: Defined by the flex-direction property (default is horizontal from left to right).
  • Cross Axis: Perpendicular to the main axis (vertical by default).

Key Terms:

  • Main Start / Main End: The start and end points of the main axis.
  • Cross Start / Cross End: The start and end points of the cross axis.

Understanding these axes is essential, as they determine how items are aligned and distributed.

Getting Started: Setting Up a Flex Container

Now that you understand the core concepts, let’s jump into using Flexbox in your code. The first step is to create a flex container. This is done using the display: flex; property, which transforms a regular block-level element into a flex container, allowing its children (flex items) to respond to Flexbox properties.

1. Creating a Flex Container

To get started, you only need to add display: flex; to a parent element. Here’s a simple example:

<!-- HTML -->
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
/* CSS */
.container {
display: flex; /* Makes this a flex container */
}
.item {
padding: 10px;
background-color: lightblue;
margin: 5px;
}

In this example:

  • The .container element is the flex container.
  • Each .item element is a flex item that automatically adjusts its size and alignment based on Flexbox properties.

2. How Flexbox Changes Element Behaviour

Before using Flexbox, elements are usually stacked vertically (block layout) or horizontally (inline layout). But with display: flex;, all flex items align in a single row by default, with flexible spacing.

3. The Basic Structure of Flexbox Layouts

Once a container is set to display: flex;, you can control its layout using additional Flexbox properties. But before we dive into those, try experimenting with the example above to see how the layout changes when display: flex; is applied.

Key Flexbox Properties for the Flex Container

Once you’ve set display: flex; on a container, you gain access to several powerful properties to control how its child elements (flex items) behave. Let’s explore the most commonly used properties that define the layout and alignment within the flex container.

1. flex-direction

This property defines the direction in which the flex items are placed within the container. By default, it’s set to row(horizontal).

Values:

  • row (default): Items align from left to right.
  • row-reverse: Items align from right to left.
  • column: Items stack from top to bottom.
  • column-reverse: Items stack from bottom to top.
.container {
display: flex;
flex-direction: column-reverse; /* Set the flex direction */
}

2. justify-content

Controls how flex items are aligned along the main axis (horizontal by default). It helps distribute extra space when items don’t occupy the entire container width.

Values:

  • flex-start (default): Items align to the start of the main axis.
  • flex-end: Items align to the end of the main axis.
  • center: Items are centred along the main axis.
  • space-between: Items are evenly spaced, with the first item at the start and the last item at the end.
  • space-around: Items are evenly spaced, with half-sized spaces on either end.
  • space-evenly: Equal spacing between all items, including the edges.
.container {
display: flex;
justify-content: space-around;
}

3. align-items

Aligns flex items along the cross axis (vertical by default). This property is useful for vertically centring items within the container.

Values:

  • stretch (default): Items stretch to fill the container’s height.
  • flex-start: Items align to the top (cross-start).
  • flex-end: Items align to the bottom (cross-end).
  • center: Items are centred along the cross axis.
  • baseline: Items align based on their text baselines.
.container {
display: flex;
align-items: center;
}

4. align-content

Used only when you have multiple lines of flex items (i.e., when items wrap onto new lines). It controls spacing between rows along the cross axis.

Values:

  • flex-start: Lines align to the top.
  • flex-end: Lines align to the bottom.
  • center: Lines are centred.
  • space-between: Equal space between lines.
  • space-around: Lines have equal space around them.
  • stretch (default): Lines stretch to fill the container.
.container {
display: flex;
flex-wrap: wrap;
align-content: space-between;
}

Key Flexbox Properties for the Flex Items

Now that you’ve learned how to control the flex container, let’s explore properties that give you control over individual flex items. These properties allow you to manage the size, spacing, and alignment of items inside the container, providing flexibility in your layouts.

1. order

This property allows you to change the order of flex items without modifying the HTML structure. By default, all items have an order value of 0.

Items with a lower value would appear first.

.item1 {
order: 2;
}

.item2 {
order: 1;
}

2. flex-grow

Determines how much a flex item will grow relative to the other items in the container. The default value is 0 (no growth).

Higher values make items expand more to fill available space

.item {
flex-grow: 1;
}
.item2 {
flex-grow: 2;
}

3. flex-shrink

Controls how items shrink when the container is too small to fit all items. The default value is 1, meaning items will shrink equally if needed.

A value of 0 prevents an item from shrinking.

.item2 {
flex-shrink: 0;
}

4. flex-basis

Defines the initial size of a flex item before space distribution occurs. It works like width or height but is more flexible in a flex context.

Can be set in pixels, percentages, or auto (default).

.item {
flex-basis: 200px;
}

5. align-self

Overrides the align-items property for individual flex items, allowing you to align a specific item differently from others.

Values: auto (default), flex-start, flex-end, center, baseline, stretch.

.item {
align-self: center;
}

This centres the selected item along the cross axis, even if the rest are aligned differently.

6. Shorthand Property: flex

You can combine flex-grow, flex-shrink, and flex-basis into a single shorthand property:

/* Syntax: */

.item {
flex: 1 1 200px; /* flex-grow, flex-shrink, flex-basis */
}

In this example: The item can grow (1), shrink (1), and has an initial size of 200px.

👏 If you have made it this far, you are almost there. Give yourself a pat on the back with a smile on your face.

And kindly give this article an applause (or 50) 😉

Common Pitfalls and Best Practices

While Flexbox is a powerful tool, it’s essential to be aware of some common mistakes that developers often encounter, along with best practices to optimise your layouts. Let’s explore how to avoid these pitfalls and build efficient, maintainable Flexbox designs.

1. Misusing flex-basis, width, and flex-grow

  • Pitfall: Setting both flex-basis and width on the same element can cause confusion and unexpected behaviour since they both control the item’s size.
  • Best Practice: Use either flex-basis or width, but not both. Typically, flex-basis is preferred within a flex context as it works seamlessly with other Flexbox properties.
.item {
flex-basis: 200px; /* Correct */
/* Avoid using width: 200px; in combination with flex properties */
}

2. Ignoring the flex-shrink Property

  • Pitfall: By default, items have flex-shrink: 1;, which means they can shrink if needed. This might cause unintended behaviour, especially if you expect an item to maintain a specific size.
  • Best Practice: If you want certain items to maintain their size, set flex-shrink: 0;.
.item {
flex-shrink: 0; /* Prevents shrinking */
}

3. Not Using align-self for Individual Item Alignment

  • Pitfall: Relying only on align-items for the entire container can limit your flexibility when some items need to be aligned differently.
  • Best Practice: Use align-self on individual items when they need a different alignment from the rest.
.item-special {
align-self: flex-end; /* Overrides the container’s alignment */
}

4. Overusing justify-content: space-around and space-evenly

  • Pitfall: While properties like space-around and space-evenly are great for evenly distributing space, they can lead to uneven spacing on smaller screens, especially in navigation menus.
  • Best Practice: Use these properties judiciously, and test your layouts on different screen sizes to ensure they look good on both mobile and desktop.

5. Forgetting to Set flex-wrap for Overflowing Items

  • Pitfall: By default, Flexbox does not wrap items, so if you have more items than can fit in one line, they may overflow the container.
  • Best Practice: Use flex-wrap: wrap; to ensure items wrap onto new lines as needed.
.container {
display: flex;
flex-wrap: wrap; /* Allows items to wrap */
}

6. Using float or inline-block with Flexbox

  • Pitfall: Mixing Flexbox with older layout techniques like float or inline-block can lead to unexpected behaviour.
  • Best Practice: Stick to Flexbox properties within a flex container. Avoid mixing older layout methods unless absolutely necessary for a specific use case.

7. Overcomplicating with Too Many Nested Flex Containers

  • Pitfall: Nesting too many flex containers can make your code harder to understand and maintain, leading to overly complex layouts.
  • Best Practice: Keep it simple. Only nest flex containers when necessary, and try to use a single flex container to handle alignment when possible.

8. Not Testing on Different Screen Sizes

  • Pitfall: Flexbox is inherently responsive, but without proper testing, you may miss issues that appear on smaller or larger screens.
  • Best Practice: Regularly test your layouts on various devices and screen resolutions to ensure they adapt correctly.

9. Avoid Hardcoding Flex Values

  • Pitfall: Using hardcoded values for properties like flex-grow or flex-basis can make your layout inflexible.
  • Best Practice: Use relative units (%, em, rem) instead of absolute units (px). This ensures your layout scales properly with different screen sizes.

Flexbox Cheat Sheet

Here’s a quick-reference guide to the most important Flexbox properties and their values. This cheat sheet will help you easily recall the key properties while working on your layouts.

Flex Container Properties

Flex Item Properties

Further Reading & Resources

If you’re looking to deepen your understanding of Flexbox or explore more advanced layout techniques, here are some recommended resources to help you continue your journey:

1. Official Documentation

2. Online Courses & Tutorials

3. Interactive Flexbox Tools

4. Cheat Sheets & Quick References

5. Books for Deeper Understanding

  • “CSS in Depth” by Keith Grant: An excellent resource for mastering modern CSS techniques, including Flexbox.
  • “Responsive Web Design with HTML5 and CSS” by Ben Frain: A great book for understanding responsive design with Flexbox and Grid.

6. GitHub Repositories & Open-Source Projects

Explore open-source projects on GitHub to see how Flexbox is used in real-world applications. Searching for “Flexbox” can lead you to repositories with practical implementations.

7. Practice & Experimentation

  • Try building your own layouts using Flexbox to solidify your skills. Sites like CodePen and JSFiddle are great platforms for experimenting with your code.

Thanks for coming this far 🎉

If this guide helped you, don’t forget to clap 👏 and share 🔄 it with fellow developers! Let’s spread the knowledge and help each other grow! 🚀

Happy coding! 💻✨

--

--

Meyoron Aghogho
Meyoron Aghogho

Written by Meyoron Aghogho

🚀 Software Engineer | 🎮 Gamer | 🏊 Swimmer | 🎶 Music Lover | 📝 Technical Writer https://linktr.ee/YoungMayor

No responses yet