skip to Main Content

Hello is there a way to reverse an order of specific child element?

 <ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
 </ul>

from this to this:

<ul>
  <li>A</li>
  <li>C</li>
  <li>B</li>
</ul>

I only want the Item C to reverse with Item B

3

Answers


  1. Flexbox items can be displayed in an arbitrary order by using the order property:

    ul {
      display: flex;
      flex-direction: column;
    }
    
    li:nth-child(2) {
      order: 2;
    }
    
    li:nth-child(3) {
      order: 1;
    }
    <ul>
      <li>A</li>
      <li>B</li>
      <li>C</li>
    </ul>
    Login or Signup to reply.
  2. You can simply do it by using below 2 steps:

    1. ul {display : flex; flex-direction: column;} this will make list in column.

    2. As you want to change order of only second child you can use
      li:nth-child(2) { order: 2;} this will change order of B to third and C to second.

    Note: Second Element of li which is B will render at last as we have not assigned order to it.

    Thanks…

    ul {
      display: flex;
      flex-direction: column;
    }
    
    li:nth-child(2) {
      order: 2;
    }
    <ul>
      <li>A</li>
      <li>B</li>
      <li>C</li>
    </ul>
    Login or Signup to reply.
  3. The order property in Flexbox grants the flexibility to arrange flex items in a customized visual order, irrespective of their original placement in the HTML structure.

    ul {
      display: flex;
      flex-direction: column;
    }
    
    li:nth-child(2) {
      order: -1; /* Reverse the order of the second child */
    }
    
    li:nth-child(3) {
      order: -2; /* Reverse the order of the third child */
    }
    <ul>
      <li>A</li>
      <li>B</li>
      <li>C</li>
    </ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search