Ordering flex items
By default, flex items are laid out in their order in the box tree.
This is the normal, common sense behavior you’ve seen in other layout types.
Most of the time, this is exactly what you want. You have some content structured in a logical way, and you want this content to be laid out in the order that reflects that logic.
Sometimes, you want the flex items to be laid out in a different order from the box tree.
Imagine you have a list of products. You start with the most important piece of information, the name of the product. But when you lay out your products cards on the page, you want the picture of the product to be laid out above the name.
In this case, you want to keep the same order in the box tree, and only change the ordering of the layout.
The order
property lets you change the order in which flex items are laid out
Two things determine the order
- If multiple flex items are in the same ordering group, then the earlier flex items in the box tree come first
Flex items pick which ordering group they want to be in
Each flex item gets to specify which group it wants to be put in through its value of the order
property. By default, that value is 0
, which means all flex items say they want to be in group 0.
By default, all flex items are in the same ordering group
In this case, only box tree order matters.
Make sure the DOM tree order makes sense before changing this layout order
The order
property doesn’t change the order of DOM nodes, or boxes in the box tree
Just as the box tree is built based on the DOM tree, so the accessibility tree is built based on the DOM tree
This means you should make sure the DOM tree makes sense first and foremost. If someone is using a screen reader, that screen reader will show you content in the DOM tree order
Ordering has nothing to do with z-index
It just doesn’t! z-index
is all about paint order, which is the order in which boxes are painted on top of one another. It doesn’t change the size or position of a box, and happens after the box has been laid out.