为什么nth-child选择器在CSS中不起作用?

时间:2018-06-30 14:26:11

标签: html css css3 css-selectors

我正在使用nth-child选择器为不同的社交list-group-item添加边框颜色。我在做什么错了?

    .list-group-item:nth-child(1) {
    	border-right: 3px solid yellow;
    }
    
    .list-group-item:nth-child(2) {
    	border-right: 3px solid red;
    }
    
    .list-group-item:nth-child(3) {
    	border-right: 3px solid green;
    }
    
    .list-group-item:nth-child(4) {
    	border-right: 3px solid blue;
    }
    
    .list-group-item:nth-child(5) {
    	border-right: 3px solid lime;
    }
    
    .list-group-item:nth-child(6) {
    	border-right: 3px solid red;
    }
   <div class=" col-xs-12 col-sm-6 col-md-4 col-lg-6">
    	<div class="views-field views-field-title">
    		<span class="field-content list-group-item">Yahoo<a href="/app/wall/content/"></a></span>
    	</div>
    </div>
    
    <div class=" col-xs-12 col-sm-6 col-md-4 col-lg-6">
    	<div class="views-field views-field-title">
    		<span class="field-content list-group-item">Googke<a href="/app/wall/content/"></a></span>
    	</div>
    </div>

2 个答案:

答案 0 :(得分:4)

nth-child是相对于其父级而言的,而.list-group-item是本例中其父级的唯一子级。您可以通过多种方式更改此设置,包括计算此处所示的最外面的元素。

.new-class:nth-child(1) .list-group-item  {
    border-right: 3px solid yellow;
}

.new-class:nth-child(2) .list-group-item  {
    border-right: 3px solid red;
}
<div class=" col-xs-12 col-sm-6 col-md-4 col-lg-6 new-class">
    <div class="views-field views-field-title">
        <span class="field-content list-group-item">Yahoo<a href="/app/wall/content/"></a></span>
    </div>
</div>

<div class=" col-xs-12 col-sm-6 col-md-4 col-lg-6 new-class">
    <div class="views-field views-field-title">
        <span class="field-content list-group-item">Googke<a href="/app/wall/content/"></a></span>
    </div>
</div>

答案 1 :(得分:0)

选择器通过按顺序引用元素的直接子元素来工作。在上面,您尝试选择声明为使用list-group-item类的span标签的子级,该子级不存在。尝试在包含要设置样式标签的所有div元素的最接近的公共父元素上尝试使用nth-of-type()选择器。类似以下内容可能会起作用:      #container span:nth-​​of-type(1){      ...      }