CSS:最后一个孩子压倒一切

时间:2015-07-15 14:31:31

标签: html css css-selectors

css with:last-child覆盖了所有其他人。

.service-teaser .item:first-child {                                     
    margin-left: 0px;                                               
    margin-right: 50px;
}                                                                       

.service-teaser .item:last-child {                                      
    margin-left: 50px;                                              
    margin-right: 0px;                                             
}    

我的html如下所示:

<div class="container service-teaser>
  <div class="row">
    <div class="col-md-4">
      <a href="#" class="item"></a>
    </div>
    <div class="col-md-4">
      <a href="#" class="item"></a>
    </div>
    <div class="col-md-4">
      <a href="#" class="item"></a>
    </div>
  </div>
</div>

现在,每个具有“item”类的元素都将被覆盖:last-child。我的问题在哪里? :/

2 个答案:

答案 0 :(得分:2)

每个.item都位于其自己的.col-md-4元素中,因此您无法使用:first-child:last-child定位它们。 .item应位于一个容器内,或者您应该定位.col-md-4个元素。例如:

.service-teaser .col-md-4:first-child .item{ 
  margin-left: 0px;                                               
  margin-right: 50px;
}

.service-teaser .col-md-4:last-child .item{ 
  margin-left: 50px;                                              
  margin-right: 0px;  
}

答案 1 :(得分:1)

您的.item元素是唯一的元素,因此是其父元素中的最后一个元素。 为了实现我认为你需要的东西:

.service-teaser .col-md-4 .item {                                      
    margin-left: 50px;                                              
    margin-right: 0px;                                             
} 

这不是一个建议的解决方案,因为您应该尝试远离使用框架类作为样式的一部分,但是通过对标记的一些小更新,您可以获得相同的结果。