DEV Community

Cover image for Understanding CSS Flexbox: A Comprehensive Guide
Jaimal Dullat
Jaimal Dullat

Posted on • Originally published at Medium

Understanding CSS Flexbox: A Comprehensive Guide

Table of Contents

Welcome to the world of CSS Flexbox! If you are tired of using floats and positioning hacks to create layout designs, you are in the right place. In this guide, we will explore everything you need to know to create flexible and responsive layouts using CSS Flexbox. We will discuss the basics of Flexbox, its properties, and how to create responsive designs using media queries. We will also dive into advanced techniques like nested Flexbox and combining Flexbox with Grid. So, tighten your seatbelts, and let’s get started!


What is CSS Flexbox?

CSS Flexbox, or the Flexible Box Layout, is a layout model in CSS designed to simplify the arrangement and alignment of items within a container, even when their sizes are unknown or dynamic. It provides a more efficient way to lay out, align, and distribute space among items, allowing for complex layouts and adaptive user interfaces with minimal and more readable code.

Flexbox primarily consists of a flex container and its direct children, known as flex items. By setting an element as a flex container, developers can control the direction, wrapping, alignment, and sizing of its immediate children with a set of intuitive CSS properties. This model offers a robust solution to many design challenges that were previously difficult to address with older CSS layout techniques.


Why was Flexbox introduced and what was its purpose?

The need for flexbox arises from the limitations and complexities of traditional layout methods such as floats and positioning. These methods can be challenging to use and control, especially when creating responsive and dynamic layouts across different devices and screen sizes.

Flexbox provides a more efficient and customizable way to manipulate the layout of elements within a container. It allows designers to create layouts that are responsive, meaning they adapt to different screen sizes, by automatically adjusting the size and position of elements.

Additionally, flexbox eliminates the need for hacks and workarounds, making it easier to maintain and update the layout code. Overall, flexbox enhances the efficiency and flexibility of designing layouts, making it an invaluable tool for web designers.


The Basics

1. Container vs. Items

In a flex context, there are two key components:

  1. The Flex Container: This is the parent element that you’ll apply display: flex or display: inline-flex to. This will turn its direct children into flex items.

  2. The Flex Items:These are the direct children of the Flex container.

CSS Flexbox: Container vs Items

2. Main Axis vs. Cross Axis

The main axis and cross axis are fundamental concepts to understand:

  • The Main Axis is defined by the flex-direction property (row by default). It can be a row(horizontal) or column(vertical).

  • The Cross Axis is perpendicular to the main axis. If the Main Axis is a row then column is a Cros Axis

CSS Flexbox: Main Axis vs Cross Axis


Flex Container Properties

1. display

This property defines a flex container.

  • display: flex: This value makes the element a block-level flex container. It takes up the full width available, causing a line break before and after the container.

  • display: inline-flex: This value makes the element an inline-level flex container. It only takes up as much width as necessary and does not cause a line break, allowing it to sit inline with other elements.

Flex Container Property: display

2. flex-direction

The flex-direction property in CSS Flexbox defines the direction in which the flex items are placed inside the flex container. This property sets the main axis, determining the direction in which flex items are stacked.

  • row (default): Left to right.

  • row-reverse: Right to left.

  • column: Top to bottom.

  • column-reverse: Bottom to top.

Flex Container Property: flex-direction

3. flex-wrap

This determines if the flex items should wrap onto multiple lines or columns when there isn’t enough space in the flex container to fit them in a single line or column.

  • nowrap (default): All flex items will try to fit onto one line or column.

  • wrap: Items will wrap onto multiple lines or columns as needed.

  • wrap-reverse: Like wrap, but in the opposite direction.

Flex Container Property: flex-wrap

4. justify-content

The justify-content property is used to align and distribute space among flex items along the main axis of the flex container. The main axis is defined by the flex-direction property, with its default being left-to-right (row).

  • flex-start (default): Items are packed toward the start of the flex-direction.

  • flex-end: Items are packed toward the end of the flex-direction.

  • center: Items are centred along the line.

  • space-between: Items are evenly distributed in the line; the first item is on the start line, and the last item is on the end line.

  • space-around: Items have even space around them. The space between the first and last items and the flex container is half the size of the space between flex items.

  • space-evenly: Items are distributed so that the spacing between any two items (and the space to the edges) is equal.

Flex Container Property: justify-content

5. align-items

The align-items property in CSS Flexbox is used to define how flex items are aligned along the cross axis of the flex container. The cross axis is perpendicular to the main axis, which is determined by the flex-direction property.

  • stretch (default): Flex items will stretch to fill the entire cross-axis size of the flex container unless they have an explicit cross size set.

  • flex-start: Flex items are aligned at the beginning of the cross axis (e.g., at the top if the flex direction is a row and at the left if the flex direction is a column).

  • flex-end: Flex items are aligned at the end of the cross axis (e.g., at the bottom if the flex direction is a row and at the right if the flex direction is a column).

  • center: Flex items are centered along the cross axis.

  • baseline: Flex items are aligned such that their baselines (the baseline of the text or content within them) align. If an item doesn’t have a baseline, the bottom margin edge is used instead.

**Note: **What is baseline ? https://en.wikipedia.org/wiki/Baseline_(typography)

Flex Container Property: align-items

6. align-content

The align-content property in CSS Flexbox determines how the flex container's lines are spaced within the flex container when there's extra space in the cross-axis. This property only takes effect when there are multiple lines of flex items, which means it's most relevant when items wrap inside a flex container.

  • stretch (default): Lines stretch to take up the remaining space. If the cross size of the container is constrained and not definite, the lines will collectively stretch to fill the free space.

  • flex-start: Lines are packed toward the start of the flex container.

  • flex-end: Lines are packed toward the end of the flex container.

  • center: Lines are packed at the center of the flex container.

  • space-between: Lines display with equal spacing between them.

  • space-around: Lines display with equal spacing around them, leading to a half-size space on the end lines.

  • space-evenly: Lines display with equal spacing between and evenly distributed, ensuring that the spacing between any two lines (and the space to the edges) is the same.

Flex Container Property: align-content

7. gap

The gap property provides a way to create space between flex items in a flex container. This space doesn’t affect the spacing around the outer edges of the flex container itself, only between the items inside.

  • gap: Represents the size of the space between flex items, both horizontally and vertically.

  • row-gap (or its older name grid-row-gap): Represents the vertical gap between flex items.

  • column-gap (or its older name grid-column-gap): Represents the horizontal gap between flex items.

Flex Container Property: gap


Flex Item Properties

1. order

The order property is applied to flex items and takes an integer value. By default, all flex items have an order value of 0.

The sequence of the flex items within the container is determined by the ascending order of the order values. Items with the same order value are displayed in their source order (i.e., the order they appear in the HTML).

Flex Item Property: order

2. flex-grow

The flex-grow property defines the ability of a flex item to grow relative to the rest of the flex items in the flex container, if necessary. It's a way to distribute extra available space among items.

Unitless Number: Represents the “flex grow factor” which determines how much of the available space in the flex container the item should take up, relative to other flex items.

  • 0 (default): The item will not grow beyond its initial size, even if there's extra space available in the container.

  • 1: The item will grow and take up one unit of the available space. If all items have flex-grow: 1, they will equally split the available space.

  • 2 or higher: Represents the proportion of the available space the item should take up. For example, in a container with two items where one has flex-grow: 1 and the other flex-grow: 2, the second item will take up twice as much of the available space as the first.

Note: The flex-grow property will only make items grow if there's additional space in the container. If there's no extra space, the property will have no effect.

Flex Item Property: flex-grow

3. flex-shrink

The flex-shrink property determines how a flex item will shrink relative to other items in the flex container when there isn't enough space on the main axis. It allows flex items to reduce in size to fit within their container.

<number>: Defines the shrink factor of the flex item. When distributing negative space (or when items need to shrink), items with higher shrink factors will shrink more than items with lower shrink factors. The default value is 1, which means every flex item will shrink equally when needed. A value of 0 will prevent the item from shrinking.

Here’s a breakdown:

  • flex-shrink: 1; (default)
  • The item can shrink if necessary. If all items have the same flex-shrink value, they will shrink at the same rate when the container is too small.

  • flex-shrink: 2;

  • The item will shrink at twice the rate of items with flex-shrink: 1 when the container is too small.

  • flex-shrink: 0;

  • The item won’t shrink, regardless of how small the flex container gets.

It’s important to note that the actual shrinking amount is determined by various factors including the size of the content, flex-basis, and other properties. The flex-shrink value acts more like a proportion indicating how much an item should shrink relative to other items in the container.

Flex Item Property: flex-shrink

4. flex-basis

The flex-basis property in CSS Flexbox defines the initial main size of a flex item. In simpler terms, it sets the default size of an item before it's resized by other Flexbox properties like flex-grow or flex-shrink.

  1. auto: This is the default value. The size is based on the item's content or, if the item has no content, its width or height properties (whichever is in the main dimension).

  2. <length>: Defines the flex basis with a fixed size using length values like px, em, rem, etc. Example: flex-basis: 250px;

  3. <percentage>: Sets the flex basis as a percentage of the parent container's size in the main axis direction. Example: flex-basis: 50%;

  4. content: This value sizes the item based on its content size. This can be useful when the size of the content is not known in advance.

Remember, flex-basis essentially determines the starting point for flex-grow and flex-shrink. After flex-basis sets the initial size, flex-grow can allocate extra space to the item, or flex-shrink can reduce the size if necessary, based on their respective values.

Flex Item Property: flex-basis

5. align-self

The align-self property in CSS Flexbox allows individual flex items to override the default alignment set by the align-items property on their flex container. It controls the alignment of that specific item along the cross axis.

  1. auto: The flex item inherits its alignment from the align-items property of its parent (the flex container) or defaults to "stretch" if not explicitly set.

  2. flex-start: Aligns the flex item at the beginning of the cross axis.

  3. flex-end: Aligns the flex item at the end of the cross axis.

  4. center: Aligns the flex item in the center of the cross axis.

  5. baseline: Aligns the flex item along the baseline of the content.

  6. stretch: The flex item will stretch to fill the container along the cross axis, unless it has a set height/width, in which case it will obey that value.

By using the align-self property, developers can create more flexible and nuanced layouts by adjusting the alignment of individual items independently from their siblings in the flex container.

Flex Item Property: align-self


Shorthand Properties

1. flex

The flex property in CSS is a shorthand that combines three properties related to the sizing and growing/shrinking behavior of flex items. It streamlines the specification of multiple flex-related properties in a single declaration.

The properties it combines are:

  1. flex-grow

  2. flex-shrink

  3. flex-basis

/* flex-grow | flex-shrink | flex-basis */
.item {
  flex: 1 0 200px;
}
Enter fullscreen mode Exit fullscreen mode

If only one value is specified, these are the interpretations:

  • If the value is a unitless number, it’s treated as flex-grow.

  • If the value is a width (e.g., 10%, 20px, etc.), it's treated as flex-basis.

The second value, when present, is always interpreted as flex-shrink.

2. flex-flow

The flex-flow property in CSS is a shorthand property for setting both the flex-direction and flex-wrap properties of a flex container. It allows you to define the primary axis of the flex container and decide whether the flex items should wrap onto multiple lines or columns.

/* flex-direction | flex-wrap */
.container {
  flex-flow: row wrap;
}
Enter fullscreen mode Exit fullscreen mode

When using shorthand properties, it’s crucial to remember the sequence of values. For flex, the sequence is flex-grow, flex-shrink, and flex-basis. For flex-flow, it's flex-direction followed by flex-wrap.


Examples

1. Sticky Footers

Keep the footer at the bottom of the viewport, especially when the content is short.

HTML:

<div class="flex-container">
  <div class="content">Main Content</div>
  <footer>Footer</footer>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS:

.flex-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

footer {
  margin-top: auto;
}
Enter fullscreen mode Exit fullscreen mode

When the footer height is fixed.

CSS:

.flex-container {
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 50px);
}

footer {
  height: 50px;
  margin-top: auto;
}
Enter fullscreen mode Exit fullscreen mode

2. Equal Height Columns

Columns that are of equal height regardless of their internal content.

HTML:

<div class="flex-container">
  <div>Short content</div>
  <div>Some longer content here, but columns remain equal height.</div>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS:

.flex-container {
  display: flex;
}
.flex-container > div {
  background-color: #f1f1f1;
  margin: 10px;
  padding: 20px;
 font-size: 30px;
}
Enter fullscreen mode Exit fullscreen mode

3. Auto-Scaling Flex Items

Let some items maintain a fixed size while others take up the remaining space.

HTML:

<div class="flex-container">
  <div class="fixed-size">Fixed</div>
  <div class="auto-size">Scales automatically</div>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS:

.flex-container {
  display: flex;
}
.flex-container > div {
  background-color: #f1f1f1;
  margin: 10px;
  padding: 20px;
  font-size: 30px;
}

.fixed-size {
  flex: 0 0 200px;
}

.auto-size {
  flex: 1;
}
Enter fullscreen mode Exit fullscreen mode

4. Nested Flex Containers

Use a flex container as a child of another flex container for complex layouts.

HTML:

 <div class="flex-parent">
  <div class="flex-child">
    <span>Item 1</span>
    <span>Item 2</span>
  </div>
  <div>Other content</div>
 </div>
Enter fullscreen mode Exit fullscreen mode

CSS:

.flex-parent {
  display: flex;
  background: #eee;
}

.flex-child {
  display: flex;
  flex-direction: column;
  background: aliceblue;
}
Enter fullscreen mode Exit fullscreen mode

5. Flexbox with Grid

Mix Flexbox and CSS Grid to achieve more complex layouts.

HTML:

<div class="grid-container">
  <div class="sidebar">
    <span>Link 1</span>
    <span>Link 2</span>
  </div>
  <div class="main-content">Main Content</div>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS:

.grid-container {
  display: grid;
  grid-template-columns: 1fr 2fr;
}

.sidebar {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Flexbox is a powerful tool for creating modern, responsive layouts that adapt to different screen sizes. By understanding the basics of flexbox properties, you can create stunning designs and improve your user experience. Keep these key points in mind to take your designs to the next level: understand flexbox axis and direction, use media queries for responsive layouts, and be aware of common flexbox issues.

🔗 Connect with me on:

Thank you for joining me on this journey through my blog!

  • Follow: Stay updated with the latest posts by hitting that follow button.

  • React: Show your appreciation with a like/other reactions if you enjoyed the article.

  • Comment: Engage in the conversation by leaving your thoughts, feedback, and questions.

  • Share: Spread the word by sharing the blog post on your social media platforms or with friends and colleagues.

Top comments (0)