DEV Community

Cory
Cory

Posted on • Originally published at corysblog.dev on

Changing the order of Flexbox items

A few months back, while I was learning all about flexbox, I came across the orderproperty. I haven’t been able to stop thinking about how cool this is and told myself if I ever start a blog, I need to talk about display:flexbox and the order property. So here we are!

There are multiple ways in which to take advantage of using the order property, but I’m just going to give the example of one use. Let’s say you have a section with your <img> followed by a <h1> and a few <p>. But by having your <img> first in your HTML markup, it makes it confusing for those using assistive devices, such as a screen reader. Your <img> will be read first by the screen reader and then your <h1>, and so on. The screen reader is going to describe an image to our viewer first without really having a context to what the website is all about. Wouldn’t it make much more sense to have the <h1> read first?

“But I want the image to be the first thing in the layout” you may say. This is the perfect opportunity to use our order property! Let’s take a look at this below;

We make a <div> which will be our “parent”. Then we have a <h1>, three <p>, and an <img>, which will all be “children” of the “parent” div.

Now, in our CSS file, if we set our <div> to the code below, nothing is going change in our layout. The HTML will still flow from top to bottom like we wrote it, but we have turned all the “children” into “flex items”.

At this point we can now “re-order” the flow of our HTML without needing to change the order it’s written in, thus enabling us to keep our accessibility.

We want to have the <img> shown first in our layout. Within our CSS file we can give each “flex item” a number and tell it how to “re-order” (1, 2, 3, 4, 5), but for that to work you MUST assign each “child” to have an order number;

This is a bit verbose for what we’re trying to do. We just want our <img> to be first and we aren’t needing to reorder the other children. So we can assign a value of “-1” to the order property which will place this “child” first without needing to give an order to the other flex items;

Here’s a codepen to better visualize and play around with.

All in all, this is a pretty simple tool to use. For some weird reason my brain finds this magical and I wanted to share!

(p.s. I believe you can use the order property with display:grid; as well. I have yet to dig into Grid, as I’m having too much fun with Flexbox!)

Top comments (0)