Reputation: 32758
I have:
<label for="modalProblemLocator">
<span>Locator</span>
<span>xxx</span>
</label>
<label for="modalProblemLocator">
<span>Locator</span>
</label>
If there are two <span>
elements inside I would like the second to be red. Is there a way I can specify a selector for the 2nd <span>
only?
What I tried was:
.inputWithLabel {
& > label span:last-child {
color: @alertColor;
}
}
But this does not work if there is just one <span>
, as then the first and only <span>
will also be the last.
Upvotes: 6
Views: 14487
Reputation: 3317
Use the nth-child in css
span{
font-size: 30px;
display: block;
}
label span{
color: blue;
}
label span:nth-child(2){
color: red;
}
<label for="modalProblemLocator">
<span>Locator</span>
<span>xxx</span>
</label>
<br><br><br><br>
<label for="modalProblemLocator">
<span>Locator</span>
</label>
<br><br><br><br>
<label for="modalProblemLocator">
<span>Locator</span>
<span>second</span>
<span>third</span>
<span>yyy</span>
<span>xxx</span>
</label>
Upvotes: 12
Reputation: 1852
span:nth-child(2)
selects every element that is the second child of its parent
span:nth-child(2) {
color: red;
}
Upvotes: 4
Reputation: 44823
Use :nth-child(2)
:
label span:nth-child(2) {
color: red;
}
<label for="modalProblemLocator">
<span>Locator</span>
<span>xxx</span>
<span>xxx</span>
<span>xxx</span>
<span>xxx</span>
</label>
<label for="modalProblemLocator">
<span>Locator</span>
</label>
Upvotes: 2