Kiee
Kiee

Reputation: 10771

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/

Upvotes: 4

Views: 4148

Answers (7)

Jacob Mattison
Jacob Mattison

Reputation: 51052

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

Upvotes: 6

user2203117
user2203117

Reputation:

Why don't you try:
body h3:first-child
The first-child pseudo element describes the element itself, not the children of the element.
The space specifies that you are looking for descendants of the body. Since you are not looking for direct descendants , you should not use >.

Upvotes: 0

Shyam
Shyam

Reputation: 792

Try This

body > div:first-child h3:first-of-type {
    color : red;
}

Upvotes: 3

StarsSky
StarsSky

Reputation: 6711

first-of-type is working well only from its parent:

h3:first-of-type
{
   color:green;
}

Html

<h3>first</h3>
<h3>second</h3>

http://jsfiddle.net/zQmR6/ does work!


If you have different div, every first h3 inside the div is considered the first one.

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

http://jsfiddle.net/RMpGq/ does not work!

Upvotes: 1

paskl
paskl

Reputation: 601

Try this:

http://jsfiddle.net/D277X/

p:nth-of-type(1) {color:yellow; }

Upvotes: -1

Ajey
Ajey

Reputation: 8202

Njoy

h3:first-of-type {
     color: red;
 }

Demo

Upvotes: -1

Musa
Musa

Reputation: 97672

The :first-of-type pseudo-class represents an element that is the first sibling of its type in the list of children of its parent element.

http://www.w3.org/TR/css3-selectors/#first-of-type-pseudo

So thats not going to work, you should just give it an id and use that to select it.

Upvotes: 1

Related Questions