0

My div sometimes starts with a p a h2 a h3 or an ul. Is there a way to select the first element of the div, regardless of what the element is?

Here is a JSFiddle https://jsfiddle.net/nv0mg602/

In the first div I would like the the first p to be red, not both p. In the second div I would like the first h2 to be red.

Thanks everyone. I've realised that .main:first-child doesn't work, but .main :first-child does (with a space between main and the colon)

Markeee
  • 523
  • 2
  • 8
  • 23

1 Answers1

1

You should use :first-child selector with child item and not parent item, and since you want to consider all the childs (whataver the tags/classes are) you have to use the universal selector * (but it's not mandatory as you can see below).

Here is an example:

.main *:first-child {
    color: red;
}
/* or simply
.main :first-child {
    color: red;
}
*/

/* or use this to select ONLY direct childs
.main > :first-child {
    color: red;
}
*/
<div class="main">
  <p>
  Hello some type
  </p>
  <p>
  And some more
  </p>
</div>

<div class="main">
  <h2>
  A heading
  </h2>
  <p>
  And some more text
  </p>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415