Mastery Games

How Flexbox Order Works

Flexbox is fantastic but it does have a few quirks that are not very intuitive. One thing that's sure to trip up new flexboxers is the order property. It doesn't behave how you'd think. The story usually goes something like this: you've got a flex item that you'd like to make sure shows up first, so you write this code:

.make-it-first-please {
  order: 1;
}

You refresh the page - feeling smug about your CSS prowess - only to see that item jump to the end of the row rather than to the beginning like you were expecting. Oh snap flexbox is broken!

Positive Order

Don't feel too bad, at least you're not alone. I asked my followers on twitter to take a guess without cheating, and the majority got it wrong:

flex positive order

The correct answer is B: the item actually moves to the back (without swapping places).

The key to making sense of flexbox order is to think of it like this:

Flex items render in ascending order (smallest to largest), defaulting to zero when not specified.

It's like while you were taking a Diet Coke break someone snuck this into the top of your stylesheet:

* {
  order: 0;
}

But now it makes sense! Giving an item order: 1 makes it come after items with the default order: 0.

Here's an example, notice the .blue with order: 1 has jumped to the end of the row, even though it was the second item in the DOM.

.container {
  display: flex;
}

.item {
  height: 200px;
  width: 200px;
}

.blue{ 
  order: 1;
}

Negative Order

Alright, so what about a negative flex order? Is that allowed? I asked a similar question to my lab rats loyal followers:

flex positive order

The correct answer here is B: the item moves to the front. This behavior seems wonky until you remember that items default order is zero, so an item with a negative order would definitely render first.

Here's an example. The .purple item has order: -1 so it jumps to the front of the line:

.container {
  display: flex;
}

.item {
  height: 200px;
  width: 200px;
}

.purple{ 
  order: -1; 
}

And that's the trick to remember:

order defaults to zero, renders in ascending order.

Makes sense now, doesn't it! Take that you crafty spec writers!

Challenge

Seeing this rule and internalizing it are two different things. Get some practice with flexbox order by shooting the zombies in Flexbox Zombies chapter 8: Out of Order. They're trying to be sneaky - switching their flexbox orders all around. Go show 'em who's boss.

Flexbox Zombies Game

Flexbox is incredibly powerful. But it's also crazy hard to master. So we all end up depending on a cheat sheet and guessing in the dev tools. Enough of that! Time to master it once and for all, in a way that actually sticks, so you can build any layout you can imagine with flexbox.Master Flexbox