Reputation: 20004
I'm trying to select the first h1
inside a div
with a class called detail_container
. It works if h1
is the first element within this div
, but if it comes after this ul
it won't work.
<style type="text/css">
.detail_container h1:first-child
{
color:blue;
}
</style>
</head>
<body>
<div class="detail_container">
<ul>
<li></li>
<li></li>
</ul>
<h1>First H1</h1>
<h1>Second H1</h1>
</div>
</body>
</html>
I was under the impression that the CSS I have will select the first h1
no matter where it is in this div
. How can I make it work?
Upvotes: 129
Views: 194705
Reputation: 201
you can also use
.detail_container h1:nth-of-type(1)
By changing the number 1 by any other number you can select any other h1 item.
Upvotes: 10
Reputation: 467
You could wrap your h1
tags in another div
and then the first one would be the first-child
. That div
doesn't even need styles. It's just a way to segregate those children.
<div class="h1-holder">
<h1>Title 1</h1>
<h1>Title 2</h1>
</div>
Upvotes: 2
Reputation: 723448
The h1:first-child
selector means
Select the first child of its parent
if and only if it's anh1
element.
The :first-child
of the container here is the ul
, and as such cannot satisfy h1:first-child
.
There is CSS3's :first-of-type
for your case:
.detail_container h1:first-of-type
{
color: blue;
}
But with browser compatibility woes and whatnot, you're better off giving the first h1
a class, then targeting that class:
.detail_container h1.first
{
color: blue;
}
Upvotes: 287
Reputation: 1591
For that particular case you can use:
.detail_container > ul + h1{
color: blue;
}
But if you need that same selector on many cases, you should have a class for those, like BoltClock said.
Upvotes: 9
Reputation: 21125
:first-child
selects the first h1
if and only if it is the first child of its parent element. In your example, the ul
is the first child of the div
.
The name of the pseudo-class is somewhat misleading, but it's explained pretty clearly here in the spec.
jQuery's :first
selector gives you what you're looking for. You can do this:
$('.detail_container h1:first').css("color", "blue");
Upvotes: 24