CSS Direct Child Selector
This article is about CSS direct child selector. In CSS, the child selector is one of the important selectors. All prospective web developers should know about this selector.
What are direct children?
<div>
<header> Some text </header>
<content> somet text </content>
<footer> some text here </footer>
</div>
The direct child appears one level down in the elements for a selected node. In the code, if you see direct children’s appear one level inside, for <div> the direct children are <header>, <content> and <footer> elements. But, <a> tag inside a <header> tag is not a direct child of a <div> element. I hope you guys have understood what is a direct child.
CSS Child Selector (>)
It is also known as a direct child selector and the symbol greater than (>) denotes the child selector in CSS. It selects any HTML element targeted by the selector written after the greater than character, which is a direct child of any HTML element targeted by the selector written before the greater than character.
Syntax of Child selector
selector1 > selector2
{
declaration list;
}
It selects any HTML element targeted by selector2, which is a direct child of any HTML element targeted by selector1.
Example of direct child
CSS:
div > p
{
border: 2px solid red;
}
HTML:
<div>
<h2>Heading Text</h2>
<p>Paragraph Text</p>
<a href="#">Anchor Text</a>
<div>
Output :
In the above HTML code, Inside the <div> are the <h2>, <p> and <a> elements. In CSS, we write to select, div > p both are tag selectors and in the flower brackets, we have written 2px red border. It selects any <p> element which is a direct child of any <div> element and applies the border. So styles apply only to p element which is a direct child of the div element.