In addition to reversing the order in which flex items are visually displayed, you can target individual items and change where they appear in the visual order with the order
property.
The order
property is designed to lay the items out in ordinal groups. What this means is that items are assigned an integer that represents their group. The items are then placed in the visual order according to that integer, lowest values first. If more than one item has the same integer value, then within that group the items are laid out as per source order.
As an example, I have 5 flex items, and assign order
values as follows:
- Source item 1:
order: 2
- Source item 2:
order: 3
- Source item 3:
order: 1
- Source item 4:
order: 3
- Source item 5:
order: 1
These items would be displayed on the page in the following order:
- Source item 3:
order: 1
- Source item 5:
order: 1
- Source item 1:
order: 2
- Source item 2:
order: 3
- Source item 4:
order: 3
You can play around with the values in this live example below and see how that changes the order. Also, try changing flex-direction
to row-reverse
and see what happens — the start line is switched so the ordering begins from the opposite side.
Flex items have a default order
value of 0
, therefore items with an integer value greater than 0 will be displayed after any items that have not been given an explicit order
value.
You can also use negative values with order
, which can be quite useful. If you want to make one item display first and leave the order of all other items unchanged, you can give that item order of -1
. As this is lower than 0 the item will always be displayed first.
In the live code example below I have items laid out using Flexbox. By changing which item has the class active
assigned to it in the HTML, you can change which item displays first and therefore becomes full width at the top of the layout, with the other items displaying below it.
The items are displayed in what is described in the specification as order-modified document order. The value of the order property is taken into account before the items are displayed.
Order also changes the paint order of the items; items with a lower value for order
will be painted first and those with a higher value for order
painted afterwards.