Posted about 5 years ago. Visible to the public.

How to reverse the order of HTML elements with CSS

Imagine you have a list you want to render inline on large screens, but stacked on small screens.

Copy
<ul> <li>high</li> <li>medium</li> <li>low</li> </ul>
Copy
ul { white-space: nowrap } /* optional: keep items in one line no matter the available width */ li { display: inline-block } @media (max-width: 600px) { li { display: block } }

Now imagine you want the rightmost item to be the topmost item on small screens. You'll need to invert the order of list items, but only for large screens. Here are some approaches to do so:

A: Float

Floating the lis to the right on large screens has the desired result:

Copy
li { float: right } @media (max-width: 600px) { li { float: none } }

However, if the ul gets its with from the lis it contains, you cannot float as it would always wrap the list items.

B: Direction

Quite hacky, but well-working is to change the writing direction of the list:

Copy
ul { direction: rtl } li { direction: ltr; /* Reset to default */ display: inline-block; } @media (max-width: 600px) { ul { direction: ltr } li { display: block } }

Note that changing the direction affects many many properties, e.g. margins, paddings, it even switches :before and :after elements.

Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Avatar
Dominik Schöler
Last edit:
about 5 years ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Dominik Schöler to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more