Skip to main content

Flexbox: What it is, what it's for, and how to use display flex

Flexbox: Introduction to Flexible Design

Discover how to use Flexbox in CSS with this comprehensive guide. Learn the container properties and flexible elements to create modern, fluid, and fully responsive web designs step by step.

What is Flexbox and why is it used in CSS?

Flexible layout, also known as Flexbox, is one of the most powerful and versatile tools in CSS for creating modern and responsive web designs. Flexbox makes it easy to align and distribute elements within a container, allowing for more dynamic and adaptable control of elements on a web page. In this article, we'll explore the basics of Flexbox, how to implement it, and some practical examples.

Advantages of using Flexbox over other layout systems

  • One-dimensional layout: Flexbox is designed to handle only one axis at a time, either horizontal or vertical. This makes it ideal for linear layouts and facilitates the alignment and distribution of elements in a single direction.

  • Alignment and distribution: Flexbox offers a wide range of properties for aligning and distributing elements within a container, such asjustify-content,align-items and align-selfThis allows for precise control over the arrangement of elements.

  • Responsiveness: Flexbox makes it easy to create responsive designs that adapt to different screen sizes and devices. Flexible elements can grow, shrink, and adjust automatically according to the available space.

  • Visual Ordering: With Flexbox, you can change the visual order of elements without altering the order in the HTML code, using the arrange property.orderThis is especially useful for improving accessibility and user experience.

  • Simplicity and readability: Flexbox CSS code is generally simpler and easier to read compared to other design methods, such as floats or absolute positioning. This facilitates maintenance and collaboration on projects.

How to activate Flexbox mode with display: flex

To start using Flexbox, you must first convert a container into a flexible container by applying the propertydisplay: flex either display: inline-flexto the parent element. This will cause all child elements within that container to behave as flex items.

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

Basic Structure: Container and Flexbox Elements

Once you've enabled Flexbox on a container, the child elements within that container become flex items. These elements can be aligned, distributed, and ordered using Flexbox's specific properties.

Flex Container Properties (Parent)

The flex container properties control the arrangement and behavior of flex items within the container. Some of the most common properties include:

###flex-direction

Defines the direction in which the flexible elements are placed (row, column, reverse row, reverse column).

###flex-wrap

Controls whether flexible elements should be adjusted to a new line when there is insufficient space in the container.

###justify-content

Align the flexible elements along the main axis (horizontal or vertical, depending on the flex direction).

###align-items

Align the flexible elements along the transverse axis (perpendicular to the main axis).

###align-content

Align the lines of flexible elements when there is extra space in the container.

Flex Item Properties (Children)

Flex item properties control the size, alignment, and order of individual elements within the flex container. Some of the most common properties include:

The Flex-Grow Property: flex-grow

This defines a flex item's ability to grow and occupy additional space in the container.

With the flex-grow property set to a positive integer, if space is available, the flex item can grow along the main axis from its flex base. Whether the item stretches to occupy all the available space on that axis, or only a portion of it, depends on whether the other elements are also allowed to grow and the value of their flex-grow properties.

Each element with a positive value consumes a portion of the available space based on its flex-grow value. If we gave all our elements in the previous example a flex-grow value of 1, then the available space in the flex container would be shared equally among our elements, and they would stretch to fill the container along the main axis. If we give our first element a flexible growth value of 2 and the other elements a value of 1 each, there are a total of 4 parts; 2 parts of the available space will be allocated to the first element (100px out of 200px in the previous example) and 1 part to each of the other two (50px each out of a total of 200px).

The Flex Shrink Property

This property defines a flex element's ability to shrink when there isn't enough space in the container.

While the flex-grow property deals with adding space to the main axis, the flex-shrink property controls how space is taken away. If we don't have enough space in the container to fit our elements and flex-shrink is set to a positive integer, then the element can become smaller than the flex base. As with flex-grow, different values can be assigned to make an element shrink faster than others: an element with a higher value set for flex-shrink will shrink faster than its siblings with lower values.

An element can shrink down to its minimum content size. This minimum size is taken into account when calculating the actual amount of shrinkage that will occur, meaning that flex shrinking can potentially appear less consistent in its behavior than flex growth. Therefore, we will examine in more detail how this algorithm works in the article "Controlling Element Proportions Along the Main Axis."

The Flex-Base Property: flex-basis

Defines the initial size of a flex element before the available space is allocated.

The flex-base defines the size of that element in terms of the space it leaves as available space. The initial value of this property is automatic; in this case, the browser checks if the element has a size. In the previous example, all elements have a width of 100 pixels. This is used as the flex-base.

If the elements do not have a size, then the size of the content is used as the flex-base. That's why when we simply declare display: flex on the parent to create flex elements, all elements move to a row and occupy only the space they need to display their content.

Shorthand values for flex properties

You will very rarely see the flex-grow, flex-shrink, and flex-basis properties used individually; instead, they are combined in the shorthand term flex. The shorthand flex allows you to set the three values in this order: flex-grow, flex-shrink, flex-basis.

NOTE

These values for flex-grow and flex-shrink are proportions. Typically, if we had all our elements set to flex: 1 1 200px and then wanted one element to grow twice as fast, we would set that element to flex: 2 1 200px. However, you can also use flex: 10 1 200px and flex: 20 1 200px if you prefer.

CSS
.box {
flex-grow: 0;
flex-shrink: 1;
flex-basis: auto;
}

/* Similar a: */

.box {
flex: 0 1 auto;
}

The Flexbase Property: align-self

Defines the alignment of a flex item along its cross axis, overriding the align-items setting of the flex container.

Flexbox Basics: Two Axes

When working with flexbox, you need to think in terms of two axes: the major axis and the cross axis. The major axis is defined by the flex-direction property, and the cross axis runs perpendicular to it. Everything we do with flexbox references these axes, so it's worth understanding how they work from the start.

The Major Axis

The major axis is defined by flex-direction, which has four possible values:

  • row
  • row-reverse
  • column
  • column-reverse

If you choose row or row-reverse, your major axis will run along the row in the inline direction.

Flex-Box Main Axis - Direction Row

Choose column or reverse column, and its main axis will run in the direction of the block, from the top of the page to the bottom.

Flex-Box Main Axis - Direction Column

The Transverse Axis

The transverse axis runs perpendicular to the main axis. Therefore, if your flexible direction (main axis) is configured in row or reverse row, the transverse axis runs along the columns.

Flex-Box Secondary Axis - Direction Row

If its major axis is a column or its inverse column, then the cross axis runs along the rows.

Flex-Box Secondary Axis - Direction Column

Start and End Lines

Another vital area to understand is how flexbox makes no assumptions about the document's writing mode. Flexbox doesn't simply assume that all lines of text start at the top left of a document and run to the right, with new lines appearing one below the other. Rather, it supports all writing modes, as well as other properties and logical values.

If theflex-direction is rowAnd if I'm working in English, then the starting edge of the main axis will be on the left and the ending edge on the right.

If I were working in Arabic, then the starting edge of my main axis would be on the right and the ending edge on the left.

In both cases, the starting edge of the cross axis is at the top of the flex container and the ending edge at the bottom, since both languages have a horizontal writing mode.

After a while, thinking in terms of start and end instead of left and right becomes natural and will be helpful when working with other layout methods, such as CSS Grid Layout, which follow the same patterns.

Flexbox and Responsive Design

How to Combine Flexbox with Media Queries

Flexbox is a powerful tool for creating responsive layouts, but sometimes it needs to be combined with media queries to achieve more precise control over how elements behave on different screen sizes. Here are some tips on how to do it:

  1. Change the direction of the main axis: You can use media queries to change this property.flex-directiondepending on the screen size. For example, you can have a row of items on large screens and switch to a column on smaller screens.
CSS
.container {
display: flex;
flex-direction: row; /* Fila por defecto */
}

@media (max-width: 600px) {
.container {
flex-direction: column; /* Cambia a columna en pantallas pequeñas */
}
}
  1. Adjusting the size of flex items: You can use media queries to change their propertiesflex-grow,flex-shrink and flex-basisThe elements adapt to different screen sizes. This allows you to control how the elements are distributed across different devices.
CSS
.item {
flex: 1 1 200px; /* Tamaño por defecto */
}

@media (max-width: 600px) {
.item {
flex: 1 1 100%; /* Ocupa todo el ancho en pantallas pequeñas */
}
}

Differences Between Flexbox and CSS Grid

Flexbox and CSS Grid are two CSS layout systems that each have their own strengths and weaknesses. Here are some key differences between them:

  • Axes: Flexbox is a one-dimensional layout system, meaning it works on only one axis at a time (horizontal or vertical). CSS Grid, on the other hand, is a two-dimensional layout system that allows you to work on both axes simultaneously.

  • Spacing Control: Flexbox excels at distributing space between elements in a single direction, while CSS Grid offers more precise control over the arrangement of elements on a grid.

  • Complexity: Flexbox is generally simpler and easier to learn than CSS Grid, making it ideal for simpler layouts. CSS Grid can be more complex, but it offers greater flexibility for more advanced designs.

  • Compatibility: Both systems are well-supported in modern browsers, but Flexbox has slightly better compatibility in older browsers.

When to Use Flexbox and When to Use Grid

  • Use Flexbox when:

  • You need to align elements in a single direction (row or column).

  • You want to distribute space between elements flexibly.

  • You are working on a simple design that doesn't require a complex grid structure.

  • Use CSS Grid when:

  • You need a two-dimensional grid structure.

  • You want precise control over the arrangement of elements in rows and columns.

  • You are working on a more complex design that requires more advanced organization of elements.

Common Mistakes and How to Avoid Them

Problems When Mixing Float and Flex

One of the most common mistakes when using Flexbox is trying to mix it with floating elements (floatFloating elements can interfere with Flexbox behavior and cause unexpected layout problems. To avoid this, make sure you don't applyfloatto elements within a flex container.

Not setting a base size

Another common mistake is not setting an appropriate base size for flex items. If a base flex size is not defined (flex-basis), the elements can behave unpredictably. Make sure to set a base size that makes sense for your design.

Common Mistakes with align-items and justify-content

The propertiesalign-items and justify-contentThese properties are fundamental for aligning and distributing elements in Flexbox. However, it's easy to make mistakes when using them. Make sure you understand how these properties work and how they affect the arrangement of elements within the flex container.

Incorrect use of flex-basis and width

The propertyflex-basisDefine the initial size of a flexible element before the available space is allocated. However, it's important not to confuseflex-basiswith the propertywidthIf both are established,flex-basisIt will take priority in a flexible container. Make sure you useflex-basisto define the initial size and avoid settingwidthUnless it's necessary.

Advanced Flexbox

Controlling Element Proportions Along the Main Axis

When working with Flexbox, it's important to understand how to control the proportions of elements along the main axis. This is achieved using propertiesflex-grow,flex-shrink and flex-basisHere are some tips for controlling element proportions:

  1. Use flex-grow to control growth: The propertyflex-growDefines the capacity of a flexible element to grow and occupy additional space in the container. You can assign different values toflex-growto make some elements grow faster than others.
CSS
.item {
flex-grow: 1; /* Todos los elementos crecen al mismo ritmo */
}

.item-1 {
flex-grow: 2; /* Este elemento crecerá al doble de velocidad */
}
  1. Use flex-shrink to control shrinkage: The propertyflex-shrinkIt defines the ability of a flexible element to shrink when there is not enough space in the container. As withflex-growyou can assign different values toflex-shrinkto make some elements shrink faster than others.
CSS
.item {
flex-shrink: 1; /* Todos los elementos se reducen al mismo ritmo */
}

.item-1 {
flex-shrink: 2; /* Este elemento se reducirá al doble de velocidad */
}
  1. Use flex-basis to define the initial size: The propertyflex-basisDefine the initial size of a flexible element before allocating it to the available space. Make sure to establish a base size that makes sense for your design.
CSS
.item {
flex-basis: 200px; /* Tamaño inicial de 200px */
}

.item-1 {
flex-basis: 300px; /* Tamaño inicial de 300px */
}

Advanced alignment with align-self and align-content

In addition to the propertiesalign-items and justify-contentFlexbox offers additional properties for more advanced alignment control:align-self and align-contentHere are some tips on how to use them:

  1. Use align-self to override the default alignment: The propertyalign-selfThis allows you to override the default alignment of a flexible element along its transverse axis. You can usealign-selfin an individual element to change its alignment without affecting the other elements in the container.
CSS
.item {
align-self: center; /* Alinea este elemento en el centro del eje transversal */
}
  1. Use align-content to align lines of flex items: The propertyalign-contentThis is used to align the lines of flex items when there is extra space in the container. This is especially useful when you have multiple lines of flex items and want to control how those lines are distributed within the container.
CSS
.container {
align-content: space-between; /* Distribuye las líneas de elementos flexibles con espacio entre ellas */
}

Performance Optimization with Flexbox

Although Flexbox is generally efficient, there are some best practices to optimize performance when using Flexbox in your designs:

  1. Minimize the use of expensive properties: Some Flexbox properties, such asflex-grow and flex-shrinkFlexbox elements can be more costly in terms of performance if overused. Try to limit their use to elements that truly need them.

  2. Avoid unnecessarily nesting flex containers: Nesting multiple flex containers can increase design complexity and impact performance. Try to keep your HTML structure as simple as possible.

  3. Use developer tools to identify performance issues: Use your browser's developer tools to monitor the performance of your Flexbox design and detect any potential problems.

Exercises

💻Get your hands on the code with these simple challenges: