Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching the order of LI elements with CSS only

Tags:

css

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/

like image 453
Philcyb Avatar asked Apr 30 '15 02:04

Philcyb


People also ask

How do I change the order of a list in CSS?

You can do it using flexbox. According to csstricks: The order property is a sub-property of the Flexible Box Layout module. Flex items are displayed in the same order as they appear in the source document by default.

How do you reverse order in CSS?

row-reverse displays the elements in reverse order horizontally, while column-reverse displays the elements in reverse order vertically.

What does Li stand for in CSS?

li stands for list item. They are the HTML tags for "bulleted" lists as opposed to "numbered" lists (which are specified by ol for ordered list).


1 Answers

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>
like image 98
Josh Crozier Avatar answered Nov 15 '22 06:11

Josh Crozier