Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my first-of-type CSS selector applying to everything?

I'm trying to target the first h3 of the page, but hitting all h3s instead. I've tried below, and with >, but that only works when it's directly inside the body and not nested.

body h3:first-of-type{ /*code*/ }

Any ideas?

I don't want to resort to adding IDs everywhere.

https://jsfiddle.net/M2X9z/

like image 823
Kiee Avatar asked Nov 03 '25 12:11

Kiee


1 Answers

First-of-type will target the first element of that type within its parent, not within the ancestor you've specified. So if your HTML was like

<body>
   <div>
      <h3>first</h3>
   </div>
   <div>
      <h3>second</h3>
   </div>
</body>

then both h3 elements will be targeted because each is the first h3 within its parent.

Given that you only want to target one element, it does seem like adding an id is the sensible approach.

(It would also be possible to do this with jQuery (which has a :first selector), though that of course would depend on javascript being enabled, and is probably overkill if you don't need it for other reasons.)

like image 141
Jacob Mattison Avatar answered Nov 05 '25 02:11

Jacob Mattison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!