如何定位嵌套类的第一个实例?

时间:2017-07-21 16:22:03

标签: html css

我试图仅从嵌套的重复块中定位类“.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>

我显然可以定位“容器”的每个实例,但我只是在页面上只获取“容器”的第一个实例。想法?

2 个答案:

答案 0 :(得分:2)

您可以使用:first-of-type/first-child定位.event_container,然后选择container

&#13;
&#13;
.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;
&#13;
&#13;

如果您想在CSS规则中更加具体,可以定位您的父home-event-block并使用子选择器>

&#13;
&#13;
#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;
&#13;
&#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)