How to reorder elements using css (CSS GRID).

August 26, 2020

Written by Thomas Duffy

Today we’re going to be talking about how to reorder items within a CSS GRID. This feature can make those tricky responsive layouts that switch the divs order for mobile and desktop views easy and trivial. Let’s get started.

In this article, we will talk about two different ways to accomplish the reordering of elements.

Using the order property to reorder elements

The first method of reordering we’re going to explore is the order property.

Below we have some basic markup that has a grid container wrapping five items. I’ve given the things some color and labels to identify the current rendering order of the items.

HTML Markup

html for order property

CSS

css for order property in css

Rendering of above code

rendering order

The order property takes a number value to determine the rendering order in the browser. What can be tricky about this property is that its default value is 0.

computed value

The reason this can be tricky because if you give the 3rd item in our example above the order value of 1, you may expect it to render at the top of the list when it reality it would render last.

reorder with order property

result of reorder property

If you intended to move item three to the top of the list, you can either set the order property of every item in the grid container so that the default value doesn’t force the element down the list or give it a negative value like this.

negative-order

item-in-first-spot

Using grid-row to order elements

Another way to reorder items is by using the grid-row property. In my opinion, this property is a little more straight forward to use. We can assign the order that we want the grid item to appear in to use’ grid-row’. For example, If I wish to the third item in the DOM to render first, I would just assign the third element a grid-row:1 and it will render in the first spot without having to worry about any of the other items in the grid-container.

grid-row

item-in-first-spot

Somethings to look out for

It’s a good idea to note that if you assign two of the same grid-items to the same grid-row. The grid will automatically add an additional column so they can both be on the same row.

grid-row

item-in-first-spot

One last thing to note is that both of these ordering techniques we went over in this post do not change the elements’ actual order in the DOM.

I hope you enjoyed this post!


Written by Thomas Duffy

Want to Build animations like the one above?

Sign up and get notified when I release my mini course on building animations with React.