Exploring the Descendant Selector in CSS: A Practical Guide


Descendant Selector (space)

A Descendant Selector in CSS is used to target and apply styles to elements that are descendants of a specific parent element. It allows you to select elements based on their hierarchical relationship within the HTML structure. The descendant selector is represented by a space between two or more selectors.

Syntax: The syntax for a descendant selector is as follows:

parent-selector descendant-selector {
  /* CSS styles go here */
}

Source Code :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Descendant Selector</title>
    <style>
      div p {
        color: green;
      }
      div p b {
        color: brown;
      }
    </style>
  </head>
  <body>
    <h2>Descendant Selector</h2>

    <p>The descendant selector matches all elements that are descendants of a specified element.</p>

    <div>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. <b>Natus molestias</b>, illum at veniam dolorem et eveniet nihil tempora vel corrupti.</p>

      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. <b>Natus molestias</b>, illum at veniam dolorem et eveniet nihil tempora vel corrupti.</p>
    </div>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus molestias, illum at veniam dolorem et eveniet nihil tempora vel corrupti.</p>
  </body>
</html>

Live Preview

The provided CSS code contains two rules that use descendant selectors to target and apply styles to specific HTML elements within a <div> element.

div p { color: green; }In simpler terms, this rule selects any <p> element that is contained within a <div> and changes its text color to green. It doesn't matter how deeply nested the <p> element is within the <div>; as long as it's a descendant of the <div>, it will be styled.

div p b { color: brown; } : In this case, the rule selects any <b> element that is nested within a <p> element, and that <p> element is, in turn, contained within a <div> element. It changes the text color of these <b> elements to brown.


CSS Tutorial


Properties Reference


Cascading Style Sheet


Flexbox Tutorial


CSS Grid Tutorial


Transitions Properties


CSS Properties with Examples


CSS Selectors


CSS Pseudo Elements


CSS Attribute Selectors


Input Pseudo Classes


CSS Examples


CSS Animation Projects