What is the descendant combinator in CSS?

The descendant combinator in CSS is a white space character () used to select elements that are descendants of another element in the document tree. This means that the selected elements are nested within the specified ancestor element, potentially through several levels of nesting.

The descendant combinator allows you to apply styles to elements that are inside of another element without having to specify the exact level of nesting between them. It is one of the most commonly used combinators in CSS as it provides a way to target nested elements without needing to be overly specific about their parent-child relationships.

Here is the general syntax of the descendant combinator:

ancestor descendant {
  /* styles */
}

In this syntax, ancestor is the selector for the parent element, and descendant is the selector for the nested element you want to style. There can be any number of elements between the ancestor and descendant.

Example

Let's consider an HTML structure:

<div class="parent">
  <p>First level</p>
  <div class="child">
    <p>Second level</p>
    <div class="grandchild">
      <p>Third level</p>
    </div>
  </div>
</div>

If you want to apply styles to all <p> elements that are descendants of the element with the class parent, you would use the descendant combinator like this:

.parent p {
  color: blue;
}

This CSS rule will apply the color blue to all <p> elements within .parent, no matter how deeply nested they are. In the above HTML, all three <p> elements would be colored blue because they are all descendants of the .parent div.

It is important to use descendant combinators with care, as they can affect performance if overused, and they can unintentionally target elements if not used precisely. When only direct children should be targeted, the child combinator (>), which is more specific, can be a better choice.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon