Web Development Basics (CSS, JavaScript,

CSS_003_Understanding Descendant and Child Selectors in C

codeaddict 2025. 1. 26. 17:15

 

In this blog post, we’ll dive into two important CSS selectors: descendant and child selectors. Understanding these will help you write precise and efficient styles for your HTML elements. Let’s explore these concepts with examples and practical code snippets.

HTML Structure

Here’s the HTML structure for this lesson:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS Selectors</title>
  <link rel="stylesheet" href="main.css">
</head>
<body>
  <ul>
    <li>Direct Child 1</li>    
    <ol>
      <li>Nested Child 1</li>
      <li>Nested Child 2</li>
    </ol>
    <li>Direct Child 1</li>
  </ul>
</body>
</html>

CSS Styles

Here’s the CSS file (main.css) used to demonstrate descendant and child selectors:

/* Descendant Selector */
ul li {
  color: black;
  font-size: 20px; /* Applies to all <li> elements within a <ul>, at any level */
}

/* Child Selector */
ul > li {
  color: green; /* Applies only to direct <li> children of the <ul> */
}

Descendant Selector ( )

The descendant selector targets all nested elements of a specified parent, regardless of how deep they are in the hierarchy.
Example in Action:
For the HTML structure above, the CSS rule ul li will apply the styles to:

  • “Direct Child 1”
  • “Nested Child 1”
  • “Nested Child 2”
  • “Direct Child 2”

This makes descendant selectors useful when you want to style all child elements, no matter their nesting level.


Child Selector (>)

The child selector, on the other hand, targets only the direct children of a parent element.
Example in Action:
For the CSS rule ul > li, only "Direct Child 1" and "Direct Child 2" will be styled, leaving "Nested Child 1" and "Nested Child 2" unaffected.

This selector is perfect when you want to limit your styles to elements that are directly inside a parent.


Visualizing the Difference

Here’s a quick summary to help differentiate:

  1. ul li → Styles all <li> elements nested inside a <ul>.
  2. ul > li → Styles only the immediate <li> children of a <ul>.

Understanding how to use descendant and child selectors effectively allows you to manage complex layouts with greater control. In the next post, we’ll explore advanced CSS combinators for even more powerful styling.