[css] :first-child not working as expected

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?

This question is related to css css-selectors

The answer is


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>

The element cannot directly inherit from <body> tag. You can try to put it in a <dir style="padding-left:0px;"></dir> tag.


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.


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.


: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");