Selector - Child Selector

About

A child selector is a selector that select child element in the DOM

A child is a direct descendant. If this is not the case, you may want a descendant selector

List

child selector (>)

A child selector matches when an element is the child of some element. A child selector is made up of two or more selectors separated by “>”.

Example(s):

  • The following rule sets the style of all P elements that are children of BODY:
body > P { line-height: 1.3 }
  • The following example combines descendant selectors and child selectors:
div ol>li p

It matches a P element that is a descendant of an LI; the LI element must be the child of an OL element; the OL element must be a descendant of a DIV. Notice that the optional whitespace around the “>” combinator has been left out.

All children element

With the * star node name selector

ul > * { /* same as ul * */
  color: blue;
}
<ul>
  <li>1</li>
  <li>2</li>
</ul>

first-child

Nothing to to with child, it select the first element in a list

Example:

  • first child of a list of anchor
a:first-child {
  color:green;
}
<a href="#">First link</a> 
<a href="#">Second link</a> 
  • first child of a node
div > *:first-child {
  color:green;
}
<div>
    <div>First Node</div> 
    <a href="#">Second Node</a> 
</div>

last-child

Select the last element in a list

Example:

  • last a
a:last-child {
  color:green;
}
<a href="#">First link</a> <a href="#">Last link</a> 
  • Complex List formatting
ul li:not(:last-child)::after {
  content: ';';
}
ul li {
  display: inline;
}
<ul>
  <li>First</li>
  <li>Second</li>
  <li>Third</li>
</ul>

nth-child

E:nth-child(xn+y) is a Tree pseudo-selector that selects in a list of E sibling, the xN+y element where N is the position element in the list.

You don't select the children of the element E.

One element

The second element in a group of siblings

  • Selects the second li in each list of child element. In our case in a ul element
/* same as li:nth-child(0n+2) */
li:nth-child(2) {
  color: blue;
}
<ul>
  <li>1</li>
  <li>2</li>
</ul>

First N element

  • First 2 elements
li:nth-child(-n+2) {
  background: blue;
  color: white;
  width:fit-content;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

Every N element

  • Modulo - Selects every 2 element among any group of li siblings
li:nth-child(2n) {
  color: white;
  background: blue;
  width:fit-content;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>