How to reverse the order of HTML elements with CSS

Posted . Visible to the public.

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

<ul>
  <li>high</li>
  <li>medium</li>
  <li>low</li>
</ul>
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:

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:

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.

Dominik Schöler
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2016-03-02 09:47)