CSS First Child when 7 or more children

2019-06-23 11:19发布

问题:

So I have this query to get the 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 as long as there is a minimum of 7. What I want to do is the opposite, get the first-child.

I tried the following

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

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

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

I know this is pretty complex CSS, and may not even be possible, but I am wondering if it can be done. I'd rather not use JS if at all possible. I guess treat this as a challenge ;)

回答1:

You can select the first element when there are 7 or more elements by using the below selector:

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

Explanation:

  • nth-last-child(n+7) - Will select all but the last seven child elements. When there are less than seven children, this will match none.
  • :first-child:nth-last-child(n+7) - Will select only the element which is also the first child among the elements which match the other part (which is, select only 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 is not working with n+7 in snippet)



回答2:

for the first element you could use the first of type in your css. Example:

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