CyberJ
CyberJ

Reputation: 1124

CSS select from last element up

I have a list which can have up to 5 items.

<ul>
 <li>One</li>
 <li>Two</li>
 <li>Three</li>
 <li>Four</li>
 <li>Five</li>
</ul>

Each list item will increment by 10% in width. I'm using:

ul li:nth-child(1) {
  width: 60%;
}
ul li:nth-child(2) {
  width: 70%;
}
ul li:nth-child(3) {
  width: 80%;
}
ul li:nth-child(4) {
  width: 90%;
}
ul li:nth-child(5) {
  width: 100%;
}

The last item should be 100%

But what happens when i have less than 5 list items? If for example, there are 3 list items, the last one will be 80%, not 100%;

I tried using:

ul li:last-child {
  width: 100%;
}

Which makes the last item full width but the preceding ones will not respect the 10% increment rule.

Is there any way to do something like...

ul li:last-child {
  width: 100%;
}
ul li:first-before-last {
  width: 90%;
}
ul li:second-before-last {
  width: 80%;
}
ul li:third-before-last {
  width: 70%;
}

and so on...

I am trying to achieve this with CSS only.

note: reversing everything and starting with the first at 100% and down is not an option. The last has to be 100% and first increment to it. It's just set up for some animations like that. I can't change it

Upvotes: 1

Views: 73

Answers (1)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

Reverse the logic and set the width starting from the last element using the :nth-last-child pseudoclass.

This approach requires to set as many selectors as the maximum cardinality of the list items.

li:nth-last-child(n + 1) {
   width: 100%
}

li:nth-last-child(n + 2) {
   width: 90%
}

li:nth-last-child(n + 3) {
   width: 80%
}

li:nth-last-child(n + 4) {
   width: 70%
}

li:nth-last-child(n + 5) {
   width: 60%
}

li:nth-last-child(n + 6) {
   width: 50%
}



li { border: 1px #9cb solid; }
<ul>
 <li>One</li>
 <li>Two</li>
 <li>Three</li>
 <li>Four</li>
 <li>Five</li>
</ul>



<ul>
 <li>One</li>
 <li>Two</li>
 <li>Three</li>
</ul>

Upvotes: 7

Related Questions