CSS for Web Development

0% completed

Previous
Next
Child combinator (>)

The child combinator, represented by a greater-than sign (>), is used to select elements that are direct children of a specific parent. Unlike the descendant combinator (a space), which selects all nested elements at any depth, the child combinator only targets the immediate child elements. This allows you to apply styles precisely to the elements that are directly nested under a parent.

Syntax

parent > child { property: value; }

Explanation:

  • parent > child:
    • This rule applies the style only to elements that are immediate children of the parent element.
    • Elements nested deeper than one level (grandchildren or beyond) will not be affected.

Example 1: Styling Direct Paragraph Children

In this example, only the <p> elements that are direct children of the .content container will have a distinct style. Paragraphs nested further inside other elements will not be targeted.

HTML

. . . .

Explanation:

  • Targeted Element:
    • The CSS rule .content > p selects only <p> elements that are immediate children of the element with the class .content.
  • Outcome:
    • The first paragraph gets red text with bold font weight.
    • The paragraph nested inside the <div> is not styled with red text because it is not a direct child.

Example 2: Styling Direct List Items in a Navigation Menu

In this example, the child combinator is used to style list items (<li>) that are direct children of the navigation menu (.nav-menu). Nested list items (if any) will not be affected by this rule.

HTML

. . . .

Explanation:

  • Direct Child Selection:
    • The rule .nav-menu > li applies only to the first-level list items inside the .nav-menu.
  • Outcome:
    • First-level list items have a light blue background, whereas nested list items (inside the "Services" item) do not inherit this styling from the child combinator rule.
    • You can add separate styling if needed for nested list items.

In summary, the child combinator (>) is a powerful tool to precisely target only the direct children of a parent element. This specificity helps in managing styles in complex documents by ensuring that only the intended elements are styled, leaving deeper nested elements untouched unless explicitly targeted.

.....

.....

.....

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