In CSS, the > selector is used to target direct child elements of a specific element. This means it selects elements that are immediately nested within another element, without any intervening elements.
Syntax
parent > child {
/* styles for the child element */
}
Example
<div class="parent">
<p>This is a direct child paragraph.</p>
<span>This is also a direct child span.</span>
<div class="child">
<p>This paragraph is a grandchild, not a direct child.</p>
</div>
</div>
.parent > p {
color: blue;
}
In this example, the CSS rule will only apply to the <p> element that is a direct child of the element with the class parent. The <p> element inside the nested <div> will not be affected.
Common Use Cases
- Styling Specific Child Elements:
- You can target specific child elements within a parent element to apply unique styles.
- Creating Layouts:
- The
>selector can be used to create complex layouts by targeting specific child elements and applying positioning, spacing, and other properties.
- The
- Overriding Default Styles:
- You can override default styles inherited from parent elements by targeting direct child elements with the
>selector.
- You can override default styles inherited from parent elements by targeting direct child elements with the
Additional Tips
- Specificity: Remember that the
>selector has a higher specificity than class selectors but lower than ID selectors. - Combining Selectors: You can combine the
>selector with other selectors to create more complex targeting rules. - CSS Preprocessors: CSS preprocessors like Sass and Less often provide features to make working with child selectors more concise and efficient.