Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

: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?

like image 992
The Muffin Man Avatar asked Dec 22 '10 02:12

The Muffin Man


People also ask

What does first child mean in CSS?

The :first-child selector allows you to target the first element immediately inside another element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.

What is the difference between first child and first of type?

The :first-child: The :first-child selector is used to select those elements which are the first-child elements. For :first-child selector the <! DOCTYPE> must be declared for IE8 and earlier versions. The :first-of-type: The :first-of-type Selector is used to targeting the first child of every element of it's parent.

How do I select the first child of a class in CSS?

The :first-child selector is used to select the specified selector, only if it is the first child of its parent.

How do you select a child element in CSS?

The CSS child selector has two selectors separated by a > symbol. The first selector indicates the parent element. The second selector indicates the child element CSS will style.


1 Answers

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; } 
like image 70
BoltClock Avatar answered Sep 16 '22 16:09

BoltClock