CSS Child Element Selector
- Previous Page CSS Descendant Selector
- Next Page CSS Adjacent Sibling Selector
Compared to descendant selectors, child selectors (Child selectors) can only select elements that are children of a certain element.
Select child elements
If you do not want to select any descendant elements but want to narrow the range to only select the children of a certain element, please use the child selector (Child selector).
For example, if you want to select only strong elements that are direct children of h1 elements, you can write it like this:
h1 > strong {color:red;}
This rule will change the two strong elements under the first h1 to red, but the strong in the second h1 is not affected:
<h1>This is <strong>very</strong> <strong>very</strong> important.</h1> <h1>This is <em>really <strong>very</strong></em> important.</h1>
Grammar Explanation
You should have noticed that the child selector uses the greater than sign (child combinator).
There can be whitespace on either side of the child combinator, which is optional. Therefore, the following writings are all correct:
h1 > strong h1> strong h1 >strong h1>strong
If read from right to left, the selector h1 > strong can be interpreted as 'select all strong elements that are children of h1 elements'.
Combining Descendant and Child Selectors
Please see the following selector:
table.company td > p
The selector above will select all p elements that are children of td elements, which themselves inherit from the table element, which has a class attribute containing 'company'.
- Previous Page CSS Descendant Selector
- Next Page CSS Adjacent Sibling Selector