CSS First child when 7 or more children

So, I have this query to get last-child when there are 7 or more elements

 li:nth-last-child(7) ~ li:last-child { background: red; } 

This works for any number of elements if at least 7 exists. I want to do the opposite, get first-child .

I tried the following

 li:nth-last-child(7) ~ li:first-child { background: red; } 

But that does not work. Strange I can get the second child using the following

 li:nth-last-child(7) ~ li:nth-child(2) { background: red; } 

I know this is pretty complicated CSS, and it may even be impossible, but I wonder if this can be done. I would prefer not to use JS, if at all possible. I suppose this is a challenge as a challenge;)

+5
source share
2 answers

You can select the first item if there are 7 or more items using the selector below:

 div:first-child:nth-last-child(n+7) { color: red; } 

Explanation:

  • nth-last-child(n+7) - will select everything except the last seven children. If there are less than seven children, this will not be appropriate.
  • :first-child:nth-last-child(n+7) - will select only the element that is also the first child among the elements that correspond to the other part (that is, select only the first child when there are seven or more children) .

 .container > div:first-child:nth-last-child(n+7) { color: red; } 
 <h3>Has seven children</h3> <div class='container'> <div>Test</div> <div>Test</div> <div>Test</div> <div>Test</div> <div>Test</div> <div>Test</div> <div>Test</div> </div> <h3>Has six children</h3> <div class='container'> <div>Test</div> <div>Test</div> <div>Test</div> <div>Test</div> <div>Test</div> <div>Test</div> </div> <h3>Has nine children</h3> <div class='container'> <div>Test</div> <div>Test</div> <div>Test</div> <div>Test</div> <div>Test</div> <div>Test</div> <div>Test</div> <div>Test</div> <div>Test</div> </div> 

Fiddle Demo (for some reason, it does not work with n+7 in the fragment)

+8
source

for the first element, you can use the first type in your css. Example:

  p:first-of-type { background: #ff0000; } 
-1
source

Source: https://habr.com/ru/post/1235355/


All Articles