Flexbox - Learn web development | MDN (2024)

  • Previous
  • Overview: CSS layout
  • Next

Flexbox is a one-dimensional layout method for arranging items in rows or columns. Items flex (expand) to fill additional space or shrink to fit into smaller spaces. This article explains all the fundamentals.

Prerequisites: HTML basics (study Introduction to HTML), and an idea of how CSS works (study Introduction to CSS.)
Objective: To learn how to use the Flexbox layout system to create web layouts.

Why Flexbox?

For a long time, the only reliable cross-browser compatible tools available for creating CSS layouts were features like floats and positioning. These work, but in some ways they're also limiting and frustrating.

The following simple layout designs are either difficult or impossible to achieve with such tools in any kind of convenient, flexible way:

  • Vertically centering a block of content inside its parent.
  • Making all the children of a container take up an equal amount of the available width/height, regardless of how much width/height is available.
  • Making all columns in a multiple-column layout adopt the same height even if they contain a different amount of content.

As you'll see in subsequent sections, flexbox makes a lot of layout tasks much easier. Let's dig in!

Introducing a simple example

In this article, you'll work through a series of exercises to help you understand how flexbox works. To get started, you should make a local copy of the first starter file — flexbox0.html from our GitHub repo. Load it in a modern browser (like Firefox or Chrome) and have a look at the code in your code editor. You can also see it live here.

Flexbox - Learn web development | MDN (1)

You'll see that we have a <header> element with a top level heading inside it and a <section> element containing three <article>s. We're going to use these to create a fairly standard three column layout.

Specifying what elements to lay out as flexible boxes

To start with, we need to select which elements are to be laid out as flexible boxes. To do this, we set a special value of display on the parent element of the elements you want to affect. In this case we want to lay out the <article> elements, so we set this on the <section>:

css

section { display: flex;}

This causes the <section> element to become a flex container and its children become flex items. This is what it looks like:

Flexbox - Learn web development | MDN (2)

This single declaration gives us everything we need. Incredible, right? We have a multiple column layout with equal-sized columns, and the columns are all the same height. This is because the default values given to flex items (the children of the flex container) are set up to solve common problems such as this.

Let's recap what's happening here. Adding a display value of flex to an element makes it a flex container. The container is displayed as Block-level content in terms of how it interacts with the rest of the page. When the element is converted to a flex container, its children are converted to (and laid out as) flex items.

You can make the container inline using an outside display value (e.g., display: inline flex), which affects how the container itself is laid out in the page. The legacy inline-flex display value displays the container as inline as well. We'll focus on how the contents of the container behave in this tutorial, but if you want to see the effect of inline versus block layout, you can have a look at the value comparison on the display property page.

The next sections explain in more detail what flex items are and what happens inside an element when you make it a flex container.

The flex model

When elements are laid out as flex items, they are laid out along two axes:

Flexbox - Learn web development | MDN (3)

  • The main axis is the axis running in the direction the flex items are laid out in (for example, as a row across the page, or a column down the page.) The start and end of this axis are called the main start and main end.
  • The cross axis is the axis running perpendicular to the direction the flex items are laid out in. The start and end of this axis are called the cross start and cross end.
  • The parent element that has display: flex set on it (the <section> in our example) is called the flex container.
  • The items laid out as flexible boxes inside the flex container are called flex items (the <article> elements in our example).

Bear this terminology in mind as you go through subsequent sections. You can always refer back to it if you get confused about any of the terms being used.

Columns or rows?

Flexbox provides a property called flex-direction that specifies which direction the main axis runs (which direction the flexbox children are laid out in). By default this is set to row, which causes them to be laid out in a row in the direction your browser's default language works in (left to right, in the case of an English browser).

Try adding the following declaration to your <section> rule:

css

flex-direction: column;

You'll see that this puts the items back in a column layout, much like they were before we added any CSS. Before you move on, delete this declaration from your example.

Note: You can also lay out flex items in a reverse direction using the row-reverse and column-reverse values. Experiment with these values too!

Wrapping

One issue that arises when you have a fixed width or height in your layout is that eventually your flexbox children will overflow their container, breaking the layout. Have a look at our flexbox-wrap0.html example and try viewing it live (take a local copy of this file now if you want to follow along with this example):

Flexbox - Learn web development | MDN (4)

Here we see that the children are indeed breaking out of their container. One way in which you can fix this is to add the following declaration to your <section> rule:

css

flex-wrap: wrap;

Also, add the following declaration to your <article> rule:

css

flex: 200px;

Try this now. You'll see that the layout looks much better with this included:

Flexbox - Learn web development | MDN (5)

We now have multiple rows. Each row has as many flexbox children fitted into it as is sensible. Any overflow is moved down to the next line. The flex: 200px declaration set on the articles means that each will be at least 200px wide. We'll discuss this property in more detail later on. You might also notice that the last few children on the last row are each made wider so that the entire row is still filled.

But there's more we can do here. First of all, try changing your flex-direction property value to row-reverse. Now you'll see that you still have your multiple row layout, but it starts from the opposite corner of the browser window and flows in reverse.

flex-flow shorthand

At this point it's worth noting that a shorthand exists for flex-direction and flex-wrap: flex-flow. So, for example, you can replace

css

flex-direction: row;flex-wrap: wrap;

with

css

flex-flow: row wrap;

Flexible sizing of flex items

Let's now return to our first example and look at how we can control what proportion of space flex items take up compared to the other flex items. Fire up your local copy of flexbox0.html, or take a copy of flexbox1.html as a new starting point (see it live).

First, add the following rule to the bottom of your CSS:

css

article { flex: 1;}

This is a unitless proportion value that dictates how much available space along the main axis each flex item will take up compared to other flex items. In this case, we're giving each <article> element the same value (a value of 1), which means they'll all take up an equal amount of the spare space left after properties like padding and margin have been set. This value is proportionally shared among the flex items: giving each flex item a value of 400000 would have exactly the same effect.

Now add the following rule below the previous one:

css

article:nth-of-type(3) { flex: 2;}

Now when you refresh, you'll see that the third <article> takes up twice as much of the available width as the other two. There are now four proportion units available in total (since 1 + 1 + 2 = 4). The first two flex items have one unit each, so they each take 1/4 of the available space. The third one has two units, so it takes up 2/4 of the available space (or one-half).

You can also specify a minimum size value within the flex value. Try updating your existing article rules like so:

css

article { flex: 1 200px;}article:nth-of-type(3) { flex: 2 200px;}

This basically states, "Each flex item will first be given 200px of the available space. After that, the rest of the available space will be shared according to the proportion units." Try refreshing and you'll see a difference in how the space is shared.

Flexbox - Learn web development | MDN (6)

The real value of flexbox can be seen in its flexibility/responsiveness. If you resize the browser window or add another <article> element, the layout continues to work just fine.

flex: shorthand versus longhand

flex is a shorthand property that can specify up to three different values:

  • The unitless proportion value we discussed above. This can be specified separately using the flex-grow longhand property.
  • A second unitless proportion value, flex-shrink, which comes into play when the flex items are overflowing their container. This value specifies how much an item will shrink in order to prevent overflow. This is quite an advanced flexbox feature and we won't be covering it any further in this article.
  • The minimum size value we discussed above. This can be specified separately using the flex-basis longhand value.

We'd advise against using the longhand flex properties unless you really have to (for example, to override something previously set). They lead to a lot of extra code being written, and they can be somewhat confusing.

Horizontal and vertical alignment

You can also use flexbox features to align flex items along the main or cross axis. Let's explore this by looking at a new example: flex-align0.html (see it live also). We're going to turn this into a neat, flexible button/toolbar. At the moment you'll see a horizontal menu bar with some buttons jammed into the top left-hand corner.

Flexbox - Learn web development | MDN (7)

First, take a local copy of this example.

Now, add the following to the bottom of the example's CSS:

css

div { display: flex; align-items: center; justify-content: space-around;}

Flexbox - Learn web development | MDN (8)

Refresh the page and you'll see that the buttons are now nicely centered horizontally and vertically. We've done this via two new properties.

align-items controls where the flex items sit on the cross axis.

  • By default, the value is stretch, which stretches all flex items to fill the parent in the direction of the cross axis. If the parent doesn't have a fixed height in the cross axis direction, then all flex items will become as tall as the tallest flex item. This is how our first example had columns of equal height by default.
  • The center value that we used in our above code causes the items to maintain their intrinsic dimensions, but be centered along the cross axis. This is why our current example's buttons are centered vertically.
  • You can also have values like flex-start and flex-end, which will align all items at the start and end of the cross axis respectively. See align-items for the full details.

You can override the align-items behavior for individual flex items by applying the align-self property to them. For example, try adding the following to your CSS:

css

button:first-child { align-self: flex-end;}

Flexbox - Learn web development | MDN (9)

Have a look at what effect this has and remove it again when you've finished.

justify-content controls where the flex items sit on the main axis.

  • The default value is flex-start, which makes all the items sit at the start of the main axis.
  • You can use flex-end to make them sit at the end.
  • center is also a value for justify-content. It'll make the flex items sit in the center of the main axis.
  • The value we've used above, space-around, is useful — it distributes all the items evenly along the main axis with a bit of space left at either end.
  • There is another value, space-between, which is very similar to space-around except that it doesn't leave any space at either end.

The justify-items property is ignored in flexbox layouts.

We'd like to encourage you to play with these values to see how they work before you continue.

Ordering flex items

Flexbox also has a feature for changing the layout order of flex items without affecting the source order. This is another thing that is impossible to do with traditional layout methods.

The code for this is simple. Try adding the following CSS to your button bar example code:

css

button:first-child { order: 1;}

Refresh and you'll see that the "Smile" button has moved to the end of the main axis. Let's talk about how this works in a bit more detail:

  • By default, all flex items have an order value of 0.
  • Flex items with higher specified order values will appear later in the display order than items with lower order values.
  • Flex items with the same order value will appear in their source order. So if you have four items whose order values have been set as 2, 1, 1, and 0 respectively, their display order would be 4th, 2nd, 3rd, then 1st.
  • The 3rd item appears after the 2nd because it has the same order value and is after it in the source order.

You can set negative order values to make items appear earlier than items whose value is 0. For example, you could make the "Blush" button appear at the start of the main axis using the following rule:

css

button:last-child { order: -1;}

Nested flex boxes

It's possible to create some pretty complex layouts with flexbox. It's perfectly OK to set a flex item to also be a flex container, so that its children are also laid out like flexible boxes. Have a look at complex-flexbox.html (see it live also).

Flexbox - Learn web development | MDN (10)

The HTML for this is fairly simple. We've got a <section> element containing three <article>s. The third <article> contains three <div>s, and the first <div> contains five <button>s:

section - article article article - div - button div button div button button button

Let's look at the code we've used for the layout.

First of all, we set the children of the <section> to be laid out as flexible boxes.

css

section { display: flex;}

Next, we set some flex values on the <article>s themselves. Take special note of the second rule here: we're setting the third <article> to have its children laid out like flex items too, but this time we're laying them out like a column.

css

article { flex: 1 200px;}article:nth-of-type(3) { flex: 3 200px; display: flex; flex-flow: column;}

Next, we select the first <div>. We first use flex: 1 100px; to effectively give it a minimum height of 100px, then we set its children (the <button> elements) to also be laid out like flex items. Here we lay them out in a wrapping row and align them in the center of the available space as we did with the individual button example we saw earlier.

css

article:nth-of-type(3) div:first-child { flex: 1 100px; display: flex; flex-flow: row wrap; align-items: center; justify-content: space-around;}

Finally, we set some sizing on the button. This time by giving it a flex value of 1 auto. This has a very interesting effect, which you'll see if you try resizing your browser window width. The buttons will take up as much space as they can. As many will fit on a line as is comfortable; beyond that, they'll drop to a new line.

css

button { flex: 1 auto; margin: 5px; font-size: 18px; line-height: 1.5;}

Test your skills!

You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Flexbox.

Summary

That concludes our tour of the basics of Flexbox. We hope you had fun and will have a good play around with it as you proceed further with your learning. Next, we'll have a look at another important aspect of CSS layouts: CSS Grids.

See also

  • Previous
  • Overview: CSS layout
  • Next
Flexbox - Learn web development | MDN (2024)

FAQs

Is flexbox difficult to learn? ›

Flexbox isn't necessarily any more difficult than the other concepts that we've covered so far, but it does have a few more moving parts. It is going to be somewhat difficult to make use of any of the things you're learning in these first lessons until you get to the end and can put it all together.

Is CSS flexbox enough? ›

I personally use flex for everything unless i need things to keep a certain amount of columns, like a list of products in an e-commerce. But flex and grid are definitely enough for 99.99% of what you need.

Is flexbox still relevant? ›

Flexbox was introduced in 2009 as a new layout system, with the goal to help us build responsive web pages and organize our elements easily, and, since then, it's gained more and more attention. It turns out it's now used as the main layout system for modern web pages.

Should I learn CSS Grid or flexbox? ›

Alignment: Aligning elements on a web page can be done in various ways, but CSS Grid and CSS Flexbox are two of the most popular methods. When comparing the two, the main difference is that CSS Grid is better suited for creating two-dimensional layouts, while CSS Flexbox is better for one-dimensional designs.

Should I learn bootstrap or flexbox? ›

The flex/grid/@media queries are very important. Bootstrap may or may not be used by a company (depends on the company) but you can't call yourself a web-developer and not know how to do layouts and media queries.

How long does it take to learn CSS flexbox? ›

How long it takes to learn CSS. Like with any programming language, understanding CSS takes both patience and practice. And the time required for this depends on many factors, but most people are able to master the fundamentals of CSS within two or three weeks of dedicated study.

What are the disadvantages of flexbox? ›

Disadvantages of Grid and Flexbox

Flexbox may be simple, but more complex flexbox layouts can get complicated real quick. Complicated layouts are also quite messy to debug. Implementing complex grids can become quite confusing to learn, especially for beginners.

Is it good practice to use flexbox? ›

Flexbox is particularly useful when it comes to styling form controls. Forms have lots of markup and lots of small elements that we typically want to align with each other.

Is flexbox easier than floats? ›

Flexbox is a css3 layout model that provides an easy and clean way to arrange items with a container. These are the following reasons to use flexbox over floats. Positioning child elements becomes easier with flexbox. Flexbox is responsive and mobile-friendly.

Does CSS Grid replace flexbox? ›

No CSS grid can't replace the flexbox. Grid and the flexbox are used to create responsive web pages.

Is Bootstrap better than CSS Grid? ›

Generally speaking, CSS grid is best for more control and flexibility over layout, especially when creating complex or asymmetrical grids. Bootstrap is ideal for quickly and easily creating responsive designs, especially when needing to use a lot of components and utilities.

Which is more responsive, grid or Flex? ›

Building a Responsive Design: Often times, user interfaces are developed to be adaptable to whatever screen they're being displayed on. In such cases, the grid layout is your best bet because it gives room to flexibility and resizing of the element.

What are the disadvantages of using flexbox? ›

One of the major drawbacks of using flexbox is performance issues. The use of flexbox can increase the page loading time if you have a larger project. You can compare the page loading time through Chrome development tools using the flexbox and the same pages constructed without using flexbox.

Is flexbox or grid better for responsive design? ›

Building a Responsive Design: Often times, user interfaces are developed to be adaptable to whatever screen they're being displayed on. In such cases, the grid layout is your best bet because it gives room to flexibility and resizing of the element.

Top Articles
Latest Posts
Article information

Author: Moshe Kshlerin

Last Updated:

Views: 5498

Rating: 4.7 / 5 (57 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Moshe Kshlerin

Birthday: 1994-01-25

Address: Suite 609 315 Lupita Unions, Ronnieburgh, MI 62697

Phone: +2424755286529

Job: District Education Designer

Hobby: Yoga, Gunsmithing, Singing, 3D printing, Nordic skating, Soapmaking, Juggling

Introduction: My name is Moshe Kshlerin, I am a gleaming, attractive, outstanding, pleasant, delightful, outstanding, famous person who loves writing and wants to share my knowledge and understanding with you.