Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot select first child in css

Here is my code

div p:first-child{
    border-left: 5px solid #bdc3c7;
}
<div>
  <h3>1 January 2018</h3>
  <h1>This is my first Article</h1>
  <p>First</p>
  <p>Second</p>
  <p>Third</p>
</div>

I want the first paragraph to have a left border. According to this MDN page, this can be done using first-child but mine doesn't work for some reason.

What's wrong with it?

like image 731
dumbPotato21 Avatar asked Sep 10 '25 18:09

dumbPotato21


1 Answers

The :first-child selector only selects the first child of its parent regardless of type. Your <p> is the third child of its <div> parent. To select the first child of a given type, use the :first-of-type instead:

div p:first-of-type {
  border-left: 5px solid #bdc3c7;
}
<div>
  <h3>1 January 2018</h3>
  <h1>This is my first Article</h1>
  <p>First</p>
  <p>Second</p>
  <p>Third</p>
</div>

EDIT To clarify how :first-child works, when you say div p:first-child, you're not selecting the first p child of any div. You're still selecting the first child of any div, but only if that child happened to be p. So it is kind of additional restriction.

In the example below, I used a cyan background for :first-child. You can see that it got applied to the two titles even though they have different types. Then I used a red border for p:first-child. You can see that this time it only got applied to the second title because it is p, and it didn't apply to the first title because it is not p (i.e. it is h3):

div :first-child {
  background-color: #0ff;
}

div p:first-child {
  border: 1px solid #f00;
}
<div>
  <h3>This is my first Article</h3>
  <p>First</p>
  <p>Second</p>
  <p>Third</p>
</div>
<div>
  <p>This is my second Article</p>
  <p>First</p>
  <p>Second</p>
  <p>Third</p>
</div>
like image 147
Racil Hilan Avatar answered Sep 13 '25 12:09

Racil Hilan