Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

CSS child selectors

 

Child Selectors

CSS child selectors select an element which is a child of another element.

If, x, y and z are three HTML elements and z resides within start and end tag of y, and y resides within start and end tag of x; then y is called as a child of x; and z is called as a child of y.

While writing child selectors, selectors must be separated with ">" combinator.

syntax:

Selector1 > Selector2 ......  { CSS-Property: value; ........................ }

Simple Example of CSS child selectors

CSS code:

p em {
color: red; /* sets color to red */ 
}

HTML code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "https://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Simple Example of CSS child selectors</title>
<link rel='stylesheet' href='Simple-Example-of-CSS-child-selector.css' type='text/css'>
</head>
<body>
<p>Lorem ipsum dolor sit amet, <em>consectetur</em> adipiscing elit. Donec a <em>urna</em> elit.</p>
</div>
</body>
</html>

Result:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a urna elit.

View this simple example of CSS child selector in a separate browser window.

Advanced Example of CSS child selectors

CSS code:

div > p > span > em {
color: red; /* sets color to red */
}

HTML code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "https://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Advanced Example of CSS child selectors</title>
<link rel='stylesheet' href='Advanced-Example-of-CSS-child-selector.css' type='text/css'>
</head>
<body>
<div>
<p><span>Lorem ipsum dolor sit amet, <em>consectetur</em> adipiscing elit.</span> <span>Donec a <em>urna</em> elit.</span></p>
</div>
</body>
</html> 

Result:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a urna elit.

View this advanced example of CSS child selector in a separate browser window.

Previous: CSS descendant selectors
Next: CSS adjacent sibling selectors