Giorgio
Giorgio

Reputation: 1970

First child selector doesn't work if header is present

I have a simple HTML with an header and some sections.

<header>Header</header>
<section>Section 1</section>
<section>Section 2</section>
<section>Section 3</section>

I would like to style the first section

section:first-child {
    background-color:green;    
}

It seems that the :first:child selector doesn't work when header is present (jsfiddle). When I remove header everything works again! Why?

Upvotes: 1

Views: 752

Answers (3)

Hashem Qolami
Hashem Qolami

Reputation: 99554

That's because the <section> is not the first child of its parent.

element:first-child represents the first child of its parent, matching the element. And in your case, the first element of the parent is a <header> element.

You could use :first-of-type pseudo-class instead.

section:first-of-type {
    background-color:green;    
}

From the MDN:

The :first-of-type CSS pseudo-class represents the first sibling of its type in the list of children of its parent element.

Upvotes: 5

should try :first-of-type psuedo class

section:first-of-type {
    background-color:green;    
}

Upvotes: 1

Vangel Tzo
Vangel Tzo

Reputation: 9313

you should apply first-of-type.

section:first-of-type {
    background-color:green;    
}

Upvotes: 2

Related Questions