css第一项选择的大孩子

时间:2017-12-21 08:12:07

标签: html css

https://jsfiddle.net/jg69c3yf/1/

我是一名css noob。 我想选择具有arrow-right的div,但它应该位于div类中,其中active是div中任意位置的第一个子节点。

在这个小提琴中,只有3个应该是绿色。

HTML

<div class="owl-stage">
<div class="owl-item">
1 
</div>
<div class="owl-item">
2 
</div>

<div class="owl-item active">
<div class="item">
 <div class="arrow-right">
3 

 </div>
</div>


</div>
<div class="owl-item active">
<div class="item">
 <div class="arrow-right">
4 
 </div>
</div>

<div class="owl-item active">
<div class="item">
 <div class="arrow-right">
5 

 </div>


</div>

</div>

CSS

.owl-stage .owl-item.active:first-child {

background-color:red;
color:blue;

}


.owl-stage .owl-item.active:first-child .arrow-right {
background-color:red;
color:Green;

}

2 个答案:

答案 0 :(得分:2)

一个问题是您的HTML中似乎缺少</div>个结束标记;当正确缩进时,这变得可见 我现在添加了</div>,所以如果我做错了你应该喊出来!

无论如何,答案是你想要的东西在CSS中是可能的,但只有你使用了一个小技巧。显然,设计师从未意识到这是必要的。诀窍是首先将“all .owl-item.active divs”着色,然后将颜色重置为“所有.owl-item.active divs跟随其他.owl-item.active divs”的默认值。

.owl-stage .owl-item.active {
  background-color: red;
  color: blue;
}

.owl-stage .owl-item.active .arrow-right {
  background-color: red;
  color: Green;
}

.owl-stage .owl-item.active ~ .owl-item.active {
  background-color: inherit;
  color: inherit;
}

.owl-stage .owl-item.active ~ .owl-item.active .arrow-right {
  background-color: inherit;
  color: inherit;
}
<div class="owl-stage">
  <div class="owl-item">
    1
  </div>
  <div class="owl-item">
    2
  </div>

  <div class="owl-item active">
    <div class="item">
      <div class="arrow-right">
        3
      </div>
    </div>
  </div>
  
  <div class="owl-item active">
    <div class="item">
      <div class="arrow-right">
        4
      </div>
    </div>
  </div> <!-- added this end tag -->
  
  <div class="owl-item active">
    <div class="item">
      <div class="arrow-right">
        5
      </div>
    </div>
  </div>
</div> <!-- and this one -->

答案 1 :(得分:1)

您可以尝试这样的事情:

.owl-stage .owl-item .arrow-right{
  background-color: red;
  color: blue;
}

/* Here you have the Selector for the first active class*/
.owl-stage .owl-item.active .arrow-right{
  background-color: white;
  color: Green;
}
/**/


/* You should put the stlye back as the first selector */
.owl-stage .owl-item.active+.owl-item .arrow-right{
  background-color: red;
  color: blue;
}
<div class="owl-stage">
  <div class="owl-item">
    1
  </div>
  <div class="owl-item">
    2
  </div>
  <div class="owl-item active">
    <div class="item">
      <div class="arrow-right">
        3
      </div>
    </div>
  </div>
  <div class="owl-item active">
    <div class="item">
      <div class="arrow-right">
        4
      </div>
    </div>
  </div>
  <div class="owl-item active">
    <div class="item">
      <div class="arrow-right">
        5
      </div>
    </div>
  </div>