Reputation: 10771
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.
Upvotes: 4
Views: 4148
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
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
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
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