如何在CSS中的h2之后将样式应用于第一个div?

时间:2017-10-16 15:03:19

标签: css

我想将第一个div颜色应用为红色。其他div为默认值。

我试过这个但没有工作。

.community_team:first-child + div{
  color:red;
}

下面的实际html

<div class="community_team">
<h2>Managers</h2>
 <div class="comm_team_item clearfix">
First Mangaer
 <div>
<div class="comm_team_item clearfix">
2nd Mangaer
 <div>
<div class="comm_team_item clearfix">
3rd Mangaer
 <div>
</div>

1 个答案:

答案 0 :(得分:3)

使用first-of-type伪选择器。在下面的示例中,这将匹配div的子元素的第一个.community_team元素。

你的div元素也没有关闭。将<div>更改为</div>即可关闭。

&#13;
&#13;
.community_team div:first-of-type {
  color: red;
}
&#13;
<div class="community_team">
  <h2>Managers</h2>
  <div class="comm_team_item clearfix">
    First Mangaer
  </div>
  <div class="comm_team_item clearfix">
    2nd Mangaer
  </div>
  <div class="comm_team_item clearfix">
    3rd Mangaer
  </div>
</div>
&#13;
&#13;
&#13;

您可以使用相邻的兄弟组合器定位div h2之后的.community-team。如果您的div之前有h2 之前的实例,但您仍希望在之后定位第一个div h2

&#13;
&#13;
.community_team h2 + div {
  color: red;
}
&#13;
<div class="community_team">
  <div>This div is prior to the h2</div>
  <h2>Managers</h2>
  <div class="comm_team_item clearfix">
    First Mangaer
  </div>
  <div class="comm_team_item clearfix">
    2nd Mangaer
  </div>
  <div class="comm_team_item clearfix">
    3rd Mangaer
  </div>
</div>
&#13;
&#13;
&#13;