Which CSS selector matches the second paragraph without using an ID?
<div>
<p>Apple</p>
<p>Mango</p>
</div>
My preference in this situation would be to use the :nth-of-type
pseudo-class:
div p:nth-of-type(2)
Why choose :nth-of-type
over :nth-child
?
Because :nth-of-type
is explicitly intended for situations (like the one you describe) where you wish to select the nth of a specific element type within a given context.
See this Working Example:
div p:nth-of-type(2) {
display: inline-block;
padding: 6px;
color: rgb(255, 255, 255);
background-color: rgb(255, 0, 0);
}
<div>
<h2>Fruit Bowl</h2>
<p>Apple</p>
<p>Mango</p>
</div>
But I can still use :nth-child
instead, right?
Yes you can - but it might not always give you the result you are expecting.
The syntax div p:nth-child(2)
doesn't mean every second p
in a given context inside the div
(like div p:nth-of-type(2)
does).
Instead it means an element which is a p
and which is also a second child.
Knowing that, which p
do you guess will be highlighted in the example below?
div p:nth-child(2) {
display: inline-block;
padding: 6px;
color: rgb(255, 255, 255);
background-color: rgb(255, 0, 0);
}
<div>
<h2>Fruit Bowl</h2>
<p>Apple</p>
<p>Mango</p>
</div>
Did you guess right?
Do you now understand the difference between :nth-of-type(2)
and :nth-child(2)
?
You could use the nth-child
selector, set to find the second child. This will select all <p>
elements that are the second child of their parent:
p:nth-child(2) {
background-color: lightblue;
}
<div>
<p>Apple</p>
<p>Mango</p>
</div>
<div>
<p>Apple</p>
<p>Mango</p>
</div>
Alternatively, if you want to find the second child in a specific set of elements, you could wrap those elements in a <div>
:
#wrapper p:nth-child(2) {
background-color: lightblue;
}
<div>
<p>Apple</p>
<p>Mango</p>
</div>
<div id="wrapper">
<p>Apple</p>
<p>Mango</p>
</div>
You should use nth-child
.
p:nth-child(2) {
color: #ccc;
}
REF: How nth child works
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With