Can someone explain to me why this doesn't work?
<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've read, the first-child selector should select the first div object from the body tag. If it's not selecting the div element, what is it selecting?
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.
The first-child is a pseudo class in CSS which represents the first element among a group of sibling elements. The :first-child Selector is used to target the first child element of it's parent for styling.
How to select an element that is the first or last child of its parent. The :first-child pseudo class means "if this element is the first child of its parent". :last-child means "if this element is the last child of its parent". Note that only element nodes (HTML tags) count, these pseudo-classes ignore text nodes.
The CSS child combinator ( > ) can be used to select all elements that are the immediate children of a specified element. A combinator combines and explains the relationship between two or more selectors.
The :first-child
pseudo-class in body:first-child
operates on the body tag, so its the body tag that is a first child of its parents that will be selected, if you want the body
's first child use the child selector
body > :first-child{
color:#f00;
}
this will give you the first child of the body.
To target the first div, you need to do body div:first-child
. Right now (I assume) you're just selecting the first-child body. (Actually I'm not entirely sure what you're selecting right now, come to think of 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 body."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With