Switching the order of LI elements with CSS only

I need to refresh an existing page using CSS already in place. I am not allowed to touch existing HTML. My only option is to create other CSS / CSS3 codes to override the existing one. No JS. No jQuery.

The following is an example of existing HTML. My target result is to create an override of CSS / CSS3 code to cancel the position, bringing the β€œsecond” class to the first in the list of orders.

I started searching about this, but I could not find any good resources. So I just thought that there might be CSS3 code that could do this, like the CSS code that I presented 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> 

From this world of CSS Code:

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

Any suggestions would be highly appreciated.

The riddle is here β†’ http://jsfiddle.net/philcyb/mL41up6t/

+5
source share
2 answers

You can make child elements of li flexbox items , and then use order to change the visual order of the elements (s).

In this case, you can set the second element to order -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 noted your question, so I doubt the browser support is worrying, considering that currently it is about 93.03% for flexboxes.


As an additional note, you can also use :nth-child / :nth-of-type 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> 
+7
source

Josh's answer is great! Another note that I used now: for mobile devices (e.g. iphone) and compatibility with other browsers, I added the following CSS codes to make it more compatible.

 #mainList { display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; -webkit-flex-direction: column; -webkit-box-orient: vertical; flex-direction: column !important; } #mainList li:nth-of-type(2) { -webkit-box-ordinal-group: 1; -moz-box-ordinal-group: 1; -ms-flex-order: 1; -webkit-order: 1; order: 1; } #mainList li:nth-of-type(1) { -webkit-box-ordinal-group: 2; -moz-box-ordinal-group: 2; -ms-flex-order: 2; -webkit-order: 2; order: 2; } 
+2
source

All Articles