Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select all elements with CSS if there are exactly 5

I want all 5 children IF there are EXACTLY 5. (If there are 4 or 6, don't select ANY children.)

To illustrate: http://jsfiddle.net/rudiedirkx/339H6/3/show/

You can select all elements if there are 1 very simply:

:first-child:last-child

You can select elements that are in the first 5 AND last 5:

:nth-child(-n+5):nth-last-child(-n+5)

(red in the demo) Both don't do what I want, but illustrate a point: 1 selector, several elements.

You can select all children IF there are 5 with 5 selectors:

li:nth-child(1):nth-last-child(5),
li:nth-child(2):nth-last-child(4),
li:nth-child(3):nth-last-child(3),
li:nth-child(4):nth-last-child(2),
li:nth-child(5):nth-last-child(1)

(yellow in the fiddle) but that's horrible. It's doubly horrible when I decide I ALSO like 4: if there are exactly 4 OR 5 elements, select them all. That would require 4 more selectors.

Is there a decent way to do this that I'm missing? I feel like :nth-child(-n+5):nth-last-child(-n+5) is on track, but that selects way too broadly. (Green in the fiddle.)

like image 331
Rudie Avatar asked Mar 24 '23 03:03

Rudie


1 Answers

You can use the general sibling combinator to select the rest of the elements after determining that the first child is also the 5th last child:

li:first-child:nth-last-child(5), 
li:first-child:nth-last-child(5) ~ li

You'll still have to repeat the selector at least once, unfortunately, as you need one to match the first child, then another with the sibling combinator to match the rest. But it definitely beats repeating it four more times.

like image 190
BoltClock Avatar answered Apr 01 '23 03:04

BoltClock