:first-child not working as expected

CssCss Selectors

Css Problem Overview


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?

Css Solutions


Solution 1 - Css

The h1:first-child selector means

> Select the first child of its parent
> if and only if it's an h1 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;
}

Solution 2 - Css

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

Solution 3 - Css

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.

Solution 4 - Css

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.

Solution 5 - Css

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThe Muffin ManView Question on Stackoverflow
Solution 1 - CssBoltClockView Answer on Stackoverflow
Solution 2 - CssRob SobersView Answer on Stackoverflow
Solution 3 - CssGrekzView Answer on Stackoverflow
Solution 4 - CssFabriceView Answer on Stackoverflow
Solution 5 - CssGhostToastView Answer on Stackoverflow