我试图仅从嵌套的重复块中定位类“.container”的第一个实例。为清晰起见,这是结构:
<div id="home-event-block>
<div class="event_container">
<div>Some Text </div>
<div class="container">More Text </div> <!-- Target this only -->
</div>
<div class="event_container">
<div>Some Text </div>
<div class="container">More Text </div>
</div>
<div class="event_container">
<div>Some Text </div>
<div class="container">More Text </div>
</div>
</div>
我显然可以定位“容器”的每个实例,但我只是在页面上只获取“容器”的第一个实例。想法?
答案 0 :(得分:2)
您可以使用:first-of-type/first-child
定位.event_container
,然后选择container
.event_container:first-of-type .container {
color: red
}
&#13;
<div id="home-event-block">
<div class="event_container">
<div>Some Text </div>
<div class="container">More Text </div>
<!-- Target this only -->
</div>
<div class="event_container">
<div>Some Text </div>
<div class="container">More Text </div>
</div>
<div class="event_container">
<div>Some Text </div>
<div class="container">More Text </div>
</div>
</div>
&#13;
如果您想在CSS规则中更加具体,可以定位您的父home-event-block
并使用子选择器>
#home-event-block>.event_container:first-of-type>.container {
color: red;
}
&#13;
<div id="home-event-block">
<div class="event_container">
<div>Some Text </div>
<div class="container">More Text </div>
<!-- Target this only -->
</div>
<div class="event_container">
<div>Some Text </div>
<div class="container">More Text </div>
</div>
<div class="event_container">
<div>Some Text </div>
<div class="container">More Text </div>
</div>
</div>
&#13;
备注:强>
"
home-event-block
:first-of-type
,因为每个兄弟都是同一个元素div
,否则您无法答案 1 :(得分:0)
一种方法是#home-event-block > div.event_container:first-of-type > div.container
#home-event-block>div.event_container:first-of-type>div.container {
color: red;
}
<div id="home-event-block">
<div class="event_container">
<div>Some Text </div>
<div class="container">More Text </div>
<!-- Target this only -->
</div>
<div class="event_container">
<div>Some Text </div>
<div class="container">More Text </div>
</div>
<div class="event_container">
<div>Some Text </div>
<div class="container">More Text </div>
</div>
</div>
这分解为:
#home-event-block
(选择ID为home-event-block
的元素)> div.event_container:first-of-type
(仅当第一个div子类具有类event_container
时才选择它)> div.container
(选择包含班级container
的div)