RockPaperLizard RockPaperLizard - 3 months ago 14
CSS Question

Is it possible to change the order of list items using CSS3?

Is it possible to change the order of list items using CSS3?

For example, if a list is coded in HTML in 1,2,3,4,5 order, but I want it to show in 5,1,2,3,4 order.

I'm using a CSS overlay to modify a Firefox extension, so I can't just change the HTML.

HTML Code



<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>




Answer

You can do it using flexbox.

Here's a fiddle I created for you: https://jsfiddle.net/x56hayht/

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

ul {
  display: flex;
  flex-direction: column;
}

ul li:first-child{
  order: 5;
}

ul li:nth-child(2){
  order: 4;
}

ul li:nth-child(3){
  order: 3;
}

ul li:nth-child(4){
  order: 2;
}

According to codepen:

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.

The order property can be used to change this ordering.

Syntax:

order: number

Hope it helps. Cheers!

Comments