JavaScript Tutorial JavaScript Examples JQuery Tutorial CSS Tutorial HTML Tutorial About Us

Lesson 6: CSS Child and Descendant Selectors


You have learned that there are four types of CSS selectors in the previous lesson. In this lesson, we shall examine a group of selectors that resemble family members that are known as child and descendant selectors. You can differentiate them from one another by examining how the elements are related.

6.1 Child Selector

The child selector comprises two elements separated by the greater than sign ">", the syntax is as follows:

element1>element2{css}

It means that element1 selects or matches element2 if and only if element2 is the direct child of element1.  In another word, it only selects one level down the HTML structure.

Example 6.1

<!DOCTYPE html>
<html>
<head>
<title> Child Selector</title>
<style>
ul>li{background-color:green;color:yellow; text-decoration:underline;}
</style>
</head>
<body>
<p>There are many types of selectors in CSS, as follows:
<ul>
<li>Universal Selector</li>
<ol>
<li>Example 1</li>
<li>Example 2</li>
</ol>
</li>
<li>Type Selector</li>
<ol>
<li>Example 1</li>
<li>Example 2</li>
</ol>
</li>
<li>ID Selector</li>
<ol>
<li>Example 1</li>
<li>Example 2</li>
</ol>
</li>
<li>Class Selector</li>
<ol>
<li>Example 1</li>
<li>Example 2</li>
</ol>
</li>
The Output

There are many types of selectors in CSS, as follows:

 6.2 The Descendant Selector

The descendant selector comprises two elements written side by side, the syntax is as follows:

element1 element2{css}

It means that element1 selects or matches element2 if element2 is a descendant of element1, where element2 includes direct and non direct children, or you can say they are grandchildren , great grandchildren and more of element 1. In another words, it selects more than one level down the html structure.

Example 6.2

<!DOCTYPE html>
<html lang="en">
<head>
<title> Child Selector</title>
<style>
ul li{background-color:green;color:yellow; text-decoration:underline;}
</style>
</head>
<body>
<p>There are many types of selectors in CSS, as follows:
<ul>
<li>Universal Selector</li>
<ol>
<li>Example 1</li>
<li>Example 2</li>
</ol>
</li>
<li>Type Selector</li>
<ol>
<li>Example 1</li>
<li>Example 2</li>
</ol>
</li>
<li>ID Selector</li>
<ol>
<li>Example 1</li>
<li>Example 2</li>
</ol>
</li>
<li>Class Selector</li>
<ol>
<li>Example 1</li>
<li>Example 2</li>
</ol>
</li>
The Output

There are many types of selectors in CSS, as follows:


❮ Previous Lesson Next Lesson ❯


Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy