Why is nth-child selector not working in css? [duplicate]
Why is nth-child selector not working in css? [duplicate]
This question already has an answer here:
I am using the nth-child selector to add border-color for different social list-group-item. What am I doing wrong?
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>
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
Just to be clear, do you want the border on the
<a href="/app/wall/content/"></a> OR the parent of that anchor element?, as it stands you have the anchor element here methinks.– Mark Schultheiss
Jun 30 at 14:41
<a href="/app/wall/content/"></a>
2 Answers
2
nth-child counts in relation to its parent, and .list-group-item is the only child of its parent in your example. You could change this in a variety of ways, including by counting the outermost elements as shown here.
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>
I am using drupal.
– Mahmoud Khosravi
Jun 30 at 14:47
The selector works by referring to direct children of an element in terms of order. Above, you're attempting to select children of the span tags declared to use the list-group-item class, which don't exist. Try instead the nth-of-type() selector on the nearest common parent of all the div elements containing the span tags that you wish to style. Something like the following would probably work:
#container span:nth-of-type(1) {
...
}
Target the parent element and then descend. jsfiddle.net/139gs7tp/1
– Manoj Kumar
Jun 30 at 14:33