Selector - Child Selector

1 - 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

3 - List

3.1 - >

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.

3.2 - first-child

On this website, this selector will select the first link


#header .description > a:first-child

3.3 - 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.

3.3.1 - 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>

3.3.2 - 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>
</ul>

3.3.3 - 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>


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap