Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find second <p> element in a <div>?

Which CSS selector matches the second paragraph without using an ID?

<div>
  <p>Apple</p>
  <p>Mango</p>
</div>
like image 411
user1476286 Avatar asked Feb 09 '13 04:02

user1476286


3 Answers

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)?

like image 145
Rounin - Glory to UKRAINE Avatar answered Nov 10 '22 12:11

Rounin - Glory to UKRAINE


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>
like image 30
Michael Peterson Avatar answered Nov 10 '22 12:11

Michael Peterson


You should use nth-child.

p:nth-child(2) {  
  color: #ccc;
}

REF: How nth child works

like image 4
Kolby Avatar answered Nov 10 '22 13:11

Kolby