Reverse Element Order with CSS Flexbox
CSS is becoming more and more powerful these days, almost to the point where the order of HTML elements output to the page no longer matters from a display standpoint -- CSS lets you do so much that almost any layout, large or small, is possible. Semantics and accessibility aside, I was recently hoping to find out if you could render elements in reverse order using only CSS, since in previous years we'd need to shift the DOM around
Let's assume we have the following HTML:
<ul"> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> <li>Five</li> <li>Six</li> <li>Seven</li> <li>Eight</li> <li>Nine</li> <li>Ten</li> </ul>
Depending upon whether you'd like the elements to display vertically or horizontally, you'll change the value of flex-direction
to reverse the order of elements:
/* show reverse by horizontal row */ .row-reverse { display: flex; flex-direction: row-reverse; } /* show reverse by vertical column */ .column-reverse { display: flex; flex-direction: column-reverse; }
row-reverse
displays the elements in reverse order horizontally, while column-reverse
displays the elements in reverse order vertically.
I recently used this technique to overcome a frustrating problem with AngularJS, whereby I was iterating over an object's keys; there was no way to iterate over these keys in reverse order from the template, so I reversed the elements with CSS. Not ideal but it did the job in the short term.
I remember when Flexbox was meant to change CSS in amazing ways, and while I don't think Flexbox's usage has changed the web world, I do think that we do have awesome tricks like this. I hope to expand my Flexbox horizons but until then I'll continue sharing snippets like this!
One BIG issue with flexbox, grid and change item order is that, when you select text on page, you select it in source order.
https://codepen.io/kartofelek007/pen/moyKwz