Read more

How to reverse the order of HTML elements with CSS

Dominik Schöler
March 02, 2016Software engineer at makandra GmbH

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 }
}
Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

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.

Posted by Dominik Schöler to makandra dev (2016-03-02 10:47)