CSS body: first child

Can someone explain to me why this is not working?

<html> <head> <style> body:first-child { color:#f00; } </style> </head> <body> <div>I should be red.</div> <div>This is not red.</div> </body> </html> 

From what I read, the first-child selector should select the first div object from the body tag. If he does not select the div element, what does he select?

+4
source share
4 answers

To target the first div, you need to make the body div:first-child . Right now (I guess) you are just choosing the body of the first child. (Actually, I'm not quite sure what you are choosing now, think about it. I don't think the first-child selector is valid to hang directly on the body tag.)

 body div:first-child { color:#f00; }​ 

This CSS will color it as you expect. Read it as "the div that is the first child of the body."

+7
source

:first-child pseudo :first-child class in body:first-child works with body tag, therefore its body tag, which is the first descendant of its parents, which will be selected if you want the first child body use a child selector

 body > :first-child{ color:#f00; } 

This will give you the first child of the body.

+7
source

Your CSS says that select any BODY element that is the first child of its parent element to be an HTML element. BUt HEAD is the first child, not BODY.

At least I think that's right :-)

+1
source

To target the first div body , you can use this,

 body div:first-of-type { /* style */ } 
0
source

All Articles