Reputation: 165
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/
Upvotes: 7
Views: 6517
Reputation: 165
Josh answer is perfect! Just an additional note that I've used just now: for mobile devices (such as iphone) and other browsers compatibility, I added the below CSS codes to make it work more compatibly.
#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;
}
Upvotes: 2
Reputation: 241008
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.
#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>
Upvotes: 9