Child Combinator selector (>)

The child combinator (>) in CSS is a powerful selector that allows you to target elements that are direct children of a specific parent element. This means it selects only the immediate children, not grandchildren or other descendants.

Syntax

parent > child {
  /* styles for the direct child */
}

Example

Let’s say you have the following HTML structure:

<div class="parent">
  <p>This is a direct child paragraph.</p>
  <div class="child">
    <p>This is a grandchild paragraph.</p>
  </div>
</div>

To style only the direct child paragraph, you would use the following CSS:

.parent > p {
  color: blue;
  font-weight: bold;
}

This CSS rule will apply the specified styles (blue color and bold font weight) only to the paragraph that is a direct child of the element with the class parent. The grandchild paragraph will not be affected.

Key Points to Remember

  • Specificity: The child combinator increases the specificity of a selector, which can be important when resolving style conflicts.
  • Efficiency: Using the child combinator can improve the performance of your CSS by reducing the number of elements that need to be checked.
  • Clarity: It can make your CSS more readable and maintainable by clearly defining the relationship between parent and child elements.