Table of Contents

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):

body > P { line-height: 1.3 }
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:

a:first-child {
  color:green;
}
<a href="#">First link</a> 
<a href="#">Second link</a> 
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:

a:last-child {
  color:green;
}
<a href="#">First link</a> <a href="#">Last link</a> 
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

/* same as li:nth-child(0n+2) */
li:nth-child(2) {
  color: blue;
}
<ul>
  <li>1</li>
  <li>2</li>
</ul>

First N element

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

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>