CSS for Web Development

0% completed

Previous
Next
Descendant combinator (Space)

The descendant combinator (a single space) lets you select elements that are nested inside another element, regardless of how deeply they are nested. It works on all levels of descendants, not just immediate children.

Syntax

ancestor descendant { property: value; }

Explanation:

  • ancestor descendant:
    • The styles will be applied to all elements (descendant) that are nested anywhere inside the ancestor element.

Example 1: Styling Paragraphs Within a Container

In this example, all <p> elements inside a container with the class .wrapper will have a specific text color. This shows how the descendant combinator targets all paragraphs nested inside the container.

HTML

. . . .

Explanation:

  • Targeting All Paragraphs:
    • .wrapper p applies styles to every <p> element inside .wrapper, regardless of depth.
  • Result:
    • Both paragraphs, even the one inside the nested <div>, receive the green text color and font size.

Example 2: Styling List Items Within a Section

In this example, we use the descendant combinator to style all list items within a <section> element. Even if the list items are inside nested <ul> elements, they inherit the same styling.

HTML

. . . .

Explanation:

  • Targeting List Items:
    • section li selects every <li> element within the <section>, including those nested inside other elements.
  • Result:
    • All list items in the section get a light yellow background, padding, and margin, creating a consistent look throughout.

These examples demonstrate how the descendant combinator uses a space between selectors to target elements nested within another element. By applying styles this way, you can simplify your CSS and maintain consistent design for elements that appear at various levels inside a container.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next