Once you’ve spent the extra time adding correct markup to your HTML list structure, it seems that there should be an easy way to reverse and re-order list items. Unfortunately the techniques to do so are relatively unknown. Many well-meaning developers give up trying to find a solution, and fall back to using paragraph markup with hand-hinted numbers. In reality, the answers are not hard, especially if you’re using HTML5.
Starting or Re-starting An Ordered List With an Arbitrary Number
By default ordered lists always start at the first counting integer. This becomes problematic if you have a list interrupted by another element, such as a paragraph:
<h2>My Top Five Movies</h2> <ol> <li>Star Wars <li>The Matrix <li>Mr. & Mrs. Smith <li>Wanted </ol> <p>Yes, I know those are Angelina Jolie movies. What can I say? I’m a fan. <ol> <li>Rashomon </ol>
The Akira Kurosawa film will be appear as 1: an ordered list always restarts by default. You can change this by using the
start attribute on the second list with an appropriate number value:
<ol start=5> <li>Rashomon </ol>
The result looks like this:
My Top Five Movies
- Star Wars
- The Matrix
- Mr. & Mrs. Smith
Yes, I know those are Angelina Jolie movies. What can I say? I’m a fan.
If you wanted to create a countdown list from 5 to 1, add
reversed to the
<h3>Countdown Sequence Start</h3> <ol reversed> <li>Ignition <li>Engine start <li>Liftoff </ol>
Countdown Sequence Start
- Engine start
Two things to note:
- This does not reverse the content, but the count. If you wanted to reverse the actual elements, you could use flexbox to do so.
reverseworks in all modern browsers, with the exception of (surprise) Microsoft Internet Explorer and Edge.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.