Switching the order of LI elements with CSS only

I need to update an existing page with CSS already in place. I am NOT allowed to touch the existing HTML. My only option is to create another CSS/CSS3 codes to override the existing one. No JS. No JQuery.

Below is a sample existing HTML. My target output is to create a CSS/CSS3 code override to reverse the position, bringing the “second” class up to be the first in the order list.

I started googling about this but i couldn’t find any good resources. So I just thought that there might be a CSS3 code that could do this like the CSS Code that I imagined below:

HTML:

<ul id="mainList">
  <li class="first">i am first</li>
  <li class="second">i am second</li>
  <li class="third">i am third</li>
</ul>

Out of this world CSS Code:

.second {
  list-position: rank(1);
}
.first {
  list-position: rank(2);
}

Any suggestions will be greatly appreciated.

Fiddle here -> http://jsfiddle.net/philcyb/mL41up6t/


solution

You could make the children li elements flexbox items and then use the order property to change the visual order of the element(s).

In this case, you could give the second element an order value of -1 so that it appears first.

Updated Example

#mainList {
  display: flex;
  flex-direction: column;
}
.second {
  order: -1;
}
<ul id="mainList">
  <li class="first">I am first</li>
  <li class="second">I am second</li>
  <li class="third">I am third</li>
</ul>

Browser support can be found here. You tagged your question with css3, so I doubt browser support is a concern considering it is currently at about ~93.03% for flexboxes.


As a side note, you can also make use of :nth-child/:nth-of-type in order to select the li element by its index rather than using classes.

#mainList {
  display: flex;
  flex-direction: column;
}
#mainList li:nth-of-type(2) {
  order: -1;
}
<ul id="mainList">
  <li>I am first</li>
  <li>I am second</li>
  <li>I am third</li>
</ul>