This tutorial discusses how to select child elements of a specific element with CSS.
Selecting Only Immediate Children with Child Combinator ( > )
The > character is a combinator that selects elements that are direct children of the parent element.
> is referred as a combinator because it combines 2 CSS selectors. The first selector is the parent, and the second selector refers to the children.
> character selects only immediate children — grand-children or grand-grand-children etc are not selected.
Example 1 :
<ul class="first-list">
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>
/* all "li" elements inside "ul.first-list" */
ul.first-list > li {
padding: 10px 0;
}
Example 2 :
<div class="parent-container">
<div class="post">
<div class="post">Post</div>
</div>
</div>
/* selects only the outer "div.post"
inner "div.post" is not selected as it is not the immediate child of ".parent-container" */
.parent-container > .post {
border: 1px solid blue;
}
Selecting Children, Grand-Children etc with Descendant Combinator ( )
The (single space) combinator selects elements that are descendants of the parent element. They can be direct children, and also can be grand-children, grand-grand-children etc.
The space character is added between 2 CSS selectors. The first is the parent, and the second is its descendant.
Example 1 :
<div class="outer">
<span>One</li>
<span>Two</li>
<span>Three</li>
</div>
/* all "span" elements inside the "div" */
div.outer span {
padding: 10px 0;
}
Example 2 :
<div class="parent-container">
<div class="post">
<div class="post">Post</div>
</div>
</div>
/* both "div.post" will be selected */
.parent-container .post {
border: 1px solid blue;
}