0
0
CSSmarkup~5 mins

Descendant selector in CSS

Choose your learning style9 modes available
Introduction
The descendant selector helps you style elements that are inside other elements, like decorating a room inside a house.
You want to change the color of all paragraphs inside a section.
You want to make all links inside a navigation bar bold.
You want to add spacing to list items inside a menu.
You want to style all buttons inside a form differently.
You want to change font size of text inside a specific container.
Syntax
CSS
ancestor descendant {
  property: value;
}
The space between ancestor and descendant means 'inside'.
It selects all descendants, no matter how deep they are nested.
Examples
This styles all links inside any <nav> element with blue color.
CSS
nav a {
  color: blue;
}
This adds space below every paragraph inside a section.
CSS
section p {
  margin-bottom: 1rem;
}
This makes all buttons inside elements with class 'container' green with white text.
CSS
.container button {
  background-color: green;
  color: white;
}
Sample Program
The CSS styles all paragraphs inside the
element with dark red color and bold text. Paragraphs outside the article keep default styles.
CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Descendant Selector Example</title>
  <style>
    article p {
      color: darkred;
      font-weight: bold;
    }
  </style>
</head>
<body>
  <article>
    <p>This paragraph is inside the article and will be dark red and bold.</p>
    <div>
      <p>This paragraph is also inside the article, nested deeper, and will be styled too.</p>
    </div>
  </article>
  <p>This paragraph is outside the article and will have default style.</p>
</body>
</html>
OutputSuccess
Important Notes
Descendant selector matches all levels inside the ancestor, not just direct children.
Use it to keep your CSS organized by targeting elements inside specific containers.
Be careful: too broad descendant selectors can slow down your page if overused.
Summary
Descendant selector uses a space between two selectors to style elements inside others.
It applies styles to all matching elements nested anywhere inside the ancestor.
Great for styling parts of your page without adding extra classes or IDs.