Descendant selector (Space)

Descendant selectors are used to target elements that are descendants of another element. A descendant selector is formed by separating two selectors with a space. The first selector targets the ancestor element, and the second selector targets the descendant element.

Syntax

ancestor selector descendant selector {
  /* styles to apply */
}

Example

p em {
  font-style: italic;
  font-weight: bold;
}

In this example:

  • p is the ancestor selector.
  • em is the descendant selector.

This rule will apply the specified styles to any em element that is a descendant of a p element.

More Complex Examples

div p a {
  color: blue;
  text-decoration: none;
}

This rule will style all anchor (a) elements that are descendants of paragraphs (p) within divs.

Specificity

When multiple selectors match an element, the browser applies the style rule with the highest specificity. Descendant selectors have lower specificity compared to more specific selectors like class and ID selectors.

Tips

  • Use descendant selectors judiciously to avoid overly complex and hard-to-maintain stylesheets.
  • Consider using more specific selectors like class or ID selectors when necessary to target elements precisely.
  • Test your styles in different browsers to ensure consistent results.