我一直试图让我的CSS选择正确的'第一个div但似乎无法隔离它。这是我的(剥离,但正确)html:
<div id="page_container">
<div></div> // this div has content, but no id or class
<div class="holder"></div> // this div has content
<div class="section"></div> // <<<< this is the div I want to select; the first div with the class 'section'
<div class="section"></div> // I don't want to select other 'section's
<div class="section"></div>
<div class="section"></div>
</div>
CSS-wise,到目前为止我已经尝试过......
#page_container > div > .section:first-child {
...rules here
}
#page_container > div:first-child(.section) { // is this even valid?
...rules here
}
#page_container > div > div > .section:first-child {
...rules here
}
......没有运气。
我可能正在经历一次大脑放屁,但是我如何才能选择第一个带有一类&#39;部分的div?
任何帮助,非常感谢!
答案 0 :(得分:4)
试试这个。
#page_container .section{
background: green;
margin: 10px 0;
}
#page_container .section ~ .section {
background: transparent;
}
<div id="page_container">
<div>this div has content, but no id or class</div>
<div class="holder">this div has content</div>
<div class="section">this is the div I want to select; the first div with the class 'section'</div>
<div class="section">I don't want to select other 'section's</div>
<div class="section"></div>
<div class="section"></div>
</div>
答案 1 :(得分:2)
您可以使用+
Combinator。
相邻兄弟组合
+组合子选择相邻的兄弟姐妹。这意味着第二个元素直接跟在第一个元素之后,并且它们共享同一个父元素。
语法:A + B
示例:h2 + p将匹配
<p>
之后的所有<h2>
元素。
参考:https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors
示例:
#page_container > .holder + .section {
background: red;
}
&#13;
<div id="page_container">
<div>this div has content, but no id or class</div>
<div class="holder">this div has content</div>
<div class="section">this is the div I want to select; the first div with the class 'section'</div>
<div class="section">I don't want to select other 'section's</div>
<div class="section"></div>
<div class="section"></div>
</div>
&#13;