Reputation: 1460
I am trying to achieve something like this
<div class="parent">
<div class="child">
<div class="item"> <!-- select this -->
<div class="item"> <!-- not this -->
</div>
</div>
</div>
</div>
I have tried using first-child
like this -
.parent .child .item:first-child p {
background: red;
}
<div class="parent">
<div class="child">
<div class="item"> <!-- select this -->
<p>This should be changed</p>
<div class="item"> <!-- not this -->
<p>This should NOT be changed</p>
</div>
</div>
</div>
</div>
But it didn't work. Is there any pure CSS way of doing it?
Upvotes: 0
Views: 56
Reputation: 11
You can also use the :first-of-type
pseudo-class.
The
:first-of-type
CSS pseudo-class represents the first element of its type among a group of sibling elements.
Here you're selecting the first div
, and then, the first p
element.
.parent > .child > .item:first-of-type > p:first-of-type {
background: red;
}
<div class="parent">
<div class="child">
<div class="item"> <!-- select this -->
<p>This should be changed</p>
<div class="item"> <!-- not this -->
<p>This should NOT be changed</p>
</div>
</div>
</div>
</div>
Upvotes: 1
Reputation: 497
You're probably looking for the child combinator:
.parent .child > .item > p {
background: red;
}
<div class="parent">
<div class="child">
<div class="item"> <!-- select this -->
<p>This should be changed</p>
<div class="item"> <!-- not this -->
<p>This should NOT be changed</p>
</div>
</div>
</div>
Upvotes: 4
Reputation: 1527
.parent .child .item:first-child > p {
background: red;
}
<div class="parent">
<div class="child">
<div class="item"> <!-- select this -->
<p>This should be changed</p>
<div class="item"> <!-- not this -->
<p>This should NOT be changed</p>
</div>
</div>
</div>
</div>
Upvotes: 1