Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS body:first-child

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?

like image 376
Xeno Avatar asked Aug 22 '12 19:08

Xeno


People also ask

How do you target the first child 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 a first child in CSS?

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 do I apply for CSS with first child and last child?

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.

How do I select immediate child in CSS?

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.


2 Answers

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.

like image 193
Musa Avatar answered Sep 24 '22 02:09

Musa


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."

like image 43
Roddy of the Frozen Peas Avatar answered Sep 27 '22 02:09

Roddy of the Frozen Peas