dfox dfox - 1 month ago 5x
CSS Question

Conditional css showing limit items

Says I have 10

, how to limit them to 5 by hiding another 5 using css? do I have to do 5 times of class like nth-child? Would it be possible to use condition in css? Because the numbers of
is dynamic, it can be 20, 30, or 100.


You can use the nth-child(n+x) selector such as:

p:nth-child(n+6) {

Here's a fiddle demonstrating with the color red for 6+

n+6 is an abbreviation for the formula equation an+b (see specs and mdn) which is iterated through for every values of "n" that are >=0 and where a and b are integers >0. So the full formula in this case it is equivalent:


Which for values of n as 0,1.. would give: 6,7... matching the 6th and up tags.

By modifying b we are able to create intervals such as:


Which for values of n as 0,1 now yields 6, 8, 10 and so on, effectively matching every other p tag starting from the 6th one.