Reputation: 1591
Didn't want to ask, but have gotten very confused on this issue with first-child.
<div class="container">
<div class="row">
<div class="col-4">
<a href="#" class="btn">Primary Button |<span> red text here</span></a>
</div>
<div class="col-4">
<a href="#" class="btn">Secondary button |<span> yellow text here</span></a>
</div>
<div class="col-4">
<a href="#" class="btn">Danger Button |<span> green text here</span></a>
</div>
</div>
</div>
the CSS I have is...
.row span:first-child {
color: red;
}
.row span {
color: yellow;
}
.row span:last-child {
color: green;
}
<div class="container">
<div class="row">
<div class="col-4">
<a href="#" class="btn">Primary Button |<span> red text here</span></a>
</div>
<div class="col-4">
<a href="#" class="btn">Secondary button |<span> yellow text here</span></a>
</div>
<div class="col-4">
<a href="#" class="btn">Danger Button |<span> green text here</span></a>
</div>
</div>
</div>
Some reason all the text color turns out 'green' because it applies all the color changes, even the red and yellow to it because it thinks that they are the first and last child of the span. How would I make it so the spans would set the correct text for each one?
Upvotes: 1
Views: 34
Reputation: 15509
You can achieve the desired effect by targeting the col-4 classes and using the same :first-child / :last-child logic. This will work because the first col-4 is a first-child of the .row div and the last on is the last-child of the .row.
Then the span inside is targeted and colored appropriately.
.col-4:first-child span {
color: red;
}
.col-4 span {
color: yellow;
}
.col-4:last-child span {
color: green;
}
<div class="container">
<div class="row">
<div class="col-4">
<a href="#" class="btn">Primary Button |<span> red text here</span></a>
</div>
<div class="col-4">
<a href="#" class="btn">Secondary button |<span> yellow text here</span></a>
</div>
<div class="col-4">
<a href="#" class="btn">Danger Button |<span> green text here</span></a>
</div>
</div>
</div>
Upvotes: 1
Reputation: 943561
because it thinks that they are the first and last child of the span.
Incorrect.
It is because the span
is the :first-child
and :last-child
of its parent element (which is the a
).
If you want to target the span
that is a descendant of the div
that is the :first-child
of its parent (that is a descendant of the .row
)… then you have to write a selector that matches the div
.
.row div:first-child span {
Upvotes: 3