Descendant and Child Selectors


Sometimes you want to style elements based on where they are inside the page.

Descendant and child selectors help you do that.

Why These Selectors Matter

Web pages are built in layers.

CSS can target elements based on their position in those layers.

Descendant Selectors

A descendant selector targets elements that are inside another element.

This styles all paragraph elements that are inside a div.

How Descendant Selectors Work

The space between selectors means "inside".

Child Selectors

A child selector targets only direct children of an element.

This styles only paragraphs that are directly inside the div.

Difference Between Descendant and Child

Descendant selector:

  • Styles all matching elements inside

Child selector:

  • Styles only direct children

Example Structure

Consider a div that contains a paragraph and a section with another paragraph inside.

Using div p will style both paragraphs.

Using div > p will style only the first one.

When to Use These Selectors

Use descendant selectors when:

  • Styling nested content

Use child selectors when:

  • You need precise control

Why This Matters for Jobs

Modern layouts rely heavily on nested elements.

Knowing how to target them properly is a key frontend skill.

Common Beginner Mistakes

  • Confusing descendant and child selectors
  • Writing selectors that are too deep and complex

Best Practice

Keep selectors simple.

Avoid very long selector chains whenever possible.

Practice Task

Create a page with nested elements and:

  • Use a descendant selector to style inner text
  • Use a child selector to style only direct children

What You Will Learn Next

In the next lesson, you will learn best practices for using selectors.