12

Given an arbitary number of flexbox children with an inline order attribute used for sorting, how would one select the last ordered element in CSS?

<ul style="display:flex">
  <li style="order: 4">a</li>
  <li style="order: 5">b</li>
  <li style="order: 3">c</li>
  <li style="order: 1">d</li>
  <li style="order: 2">e</li>
</ul>

:last-of-type doesn't work on flex children, and the list can be any length, so selecting by order index isn't an option. I'm not interested in JavaScript solutions.

silverwind
  • 3,296
  • 29
  • 31

3 Answers3

3

The only close solution to this is may be

div[style="order: 6"] {
    background-color: yellow;
}

And this will color the background with yellow for the 6th order, but since we don't know the length of the array, it seems like you'll need some javascript or jQuery with similar selector sintaxis where the number 6 in this case will be a variable with the array's length.

Marin Takanov
  • 1,079
  • 3
  • 19
  • 36
0

Adding to @Marin Takanov's answer above, this method will only work when setting the order style inline. It fails when hooking into an order set in the stylesheet ...which is annoying if you only have access to the stylesheet but not the actual code.

HTML

<ul>
  <li id="o4" style="order: 4">4</li>
  <li id="o5" style="order: 5">5</li>
  <li id="o6" style="order: 6">6</li>
  <li id="o3">3</li> <!-- Fails -->
  <li id="o1" style="order: 1">1</li>
  <li id="o2" style="order: 2">2
    <ul>
      <li id="o2s1" style="order: 1">a</li>
      <li id="o2s2" style="order: 2">b</li>
      <li id="o2s6" style="order: 6">f</li>
      <li id="o2s3">c</li> <!-- Fails -->
      <li id="o2s4" style="order: 4">d</li>
      <li id="o2s5" style="order: 5">e</li>
    </ul>
  </li>
</ul>

SCSS:

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

  li#o3 {
    order: 3;
  }

  li[style="order: 3"] {
    background-color: red;
  }

  li#o6 {
    order: 6;
  }

  li[style="order: 6"] {
    background-color: yellow;
  }
}

JSFiddle:

https://stackoverflow.com/a/29719382/1522214

Eric Norcross
  • 4,177
  • 4
  • 28
  • 53
-1

Your code isnt complete. You have to provide a flex wrapper to your divs (display: flex), so that =order: will validate. Therefore, .wrapper div:last-child should do the trick.

designarti
  • 609
  • 1
  • 8
  • 18