在CSS中我想选择三个第一个div.我有这个代码:
@H_502_2@div:nth-child(3n) {
background: red;
}
@H_502_2@<div>
Lorem ipsum dolor sit amet,consectetur adipisicing elit. Tempore laborum necessitatibus nobis obcaecati,mollitia,eos sint dolor odit. Possimus dolores recusandae sed totam,voluptatibus,voluptatum. Voluptatibus minus aut,quam ratione.
</div>
<div>
Lorem ipsum dolor sit amet,consectetur adipisicing elit. Voluptates perferendis et SAEpe omnis nemo,dolores quia ipsam ea blanditiis quaerat autem aut id itaque magnam recusandae sint architecto! Error,consequuntur.
</div>
<div>
Lorem ipsum dolor sit amet,consectetur adipisicing elit. Rem doloremque quis perspiciatis vel odio impedit itaque laborum eveniet quasi aperiam,autem cumque vero recusandae,voluptates et nesciunt quibusdam aliquid! Deleniti.
</div>
<div>
Lorem ipsum dolor sit amet,voluptates et nesciunt quibusdam aliquid! Deleniti.
</div>
我尝试上面的CSS,但它不起作用.
解决方法
它没有按预期工作,因为:nth-child(3n)将选择每个第三个元素.
您需要选择从第三个元素开始向后计数的每个元素,因此您可以使用-n 3或-1n 3.
换句话说,给定模式a b,a应该是1(或省略),因为您不想跳过元素.另外,a也应该是负数,b应该是3,因为你从第三个元素开始.
@H_502_2@div:nth-child(-1n + 3) { background: #f00; } @H_502_2@<div>One</div> <div>Two</div> <div>Three</div> <div>Four</div> <div>Five</div>值得指出的是div:nth-child(-1n 3)只会选择元素,如果它是前三个元素之一,也是元素类型div.换句话说,如果第三个元素是span,则只选择前两个div元素:
@H_502_2@div:nth-child(-1n + 3) { background: red; } @H_502_2@<div>First div</div> <div>Second div</div> <span>Span</span> <div>Third div</div>如果元素类型不同(如上所述),那么您应该使用:nth-of-type()
: