Using order to rearrange flexbox children

Share this video with your friends

Send Tweet
Published 7 years ago
Updated 3 years ago

Using the order property we alter the order in which flexbox children appear on the page, without making changes to the dom.

[00:00] On children of flexbox containers, we can adjust the order property to affect the order in which the children are displayed. Let's look at an example. Here are four primary sections on the page, a header, a navigation, the content and a footer. I'm going to uncomment this block to add some background colors to make it easier to distinguish them.

[00:19] We're going to use the order property to implement the footer anchor UI pattern where, on smaller screens, the main navigation is moved to the footer of the page to free up some real estate in the initial view.

[00:31] First, we need to change the containers display to flex. In this case, it would be the body tag. We still want the content to flow vertically. Let's change flex direction to column. Now to reorder the elements, we need to change the order property on the individual children themselves.

[00:47] Order defaults to zero. When multiple children have the same order value, those children are laid out based on the order they appear in the dom.

[00:56] If I change the order to one on the main nav, it jumps below the rest, which have an order value of zero. If I wanted the nav to appear just above the footer, I would need to adjust the footer's order value to one as well.

[01:09] Negative values are also allowed, which would let the navigation jump above the rest of the zero order elements.