如何选择放在h1元素后面的第4个元素

M.A*_*A.S 3 html css css-selectors

我需要选择放在h1元素之后的第4个div元素,我认为我的方式不是专业的方式,css中有指定的选择器吗?请注意,我必须在不向div添加id或class属性的情况下执行此操作.

h1+div+div+div+div{
background-color:red; 
}

<h1>css</h1>

<div>just some text here,</div><hr>
<div>just some text here,</div><hr>
<div>just some text here,</div><hr>
<div>just some text here,</div><hr>
<div>just some text here,</div><hr>
Run Code Online (Sandbox Code Playgroud)

And*_*L64 6

您可以使用选择它,nth-of-type然后在此之后subsequent sibling combinator选择第4个:divh1

h1~div:nth-of-type(4) {
    background-color:red;
}
Run Code Online (Sandbox Code Playgroud)

~在CSS被称为后续兄弟组合子,其可用于选择其中第一和第二元件类型共享一个父和第一元件先于文档中的第二元件类型的第二元素类型.


jsFiddle: https ://jsfiddle.net/AndrewL64/crq43gs5/


如果您确定在您之间没有任何hr标签或其他元素divs,则可以使用,nth-child但必须使用5而不是4,因为〜也计算h1标签.它看起来像这样:

h1~div:nth-child(5) {
    background-color:red;
}
Run Code Online (Sandbox Code Playgroud)

jsFiddle: https ://jsfiddle.net/AndrewL64/crq43gs5/1/