CSS :first-child Selector

The :first-child selector is used to select the specified selector, only if it is the first child of its parent.

CSS Syntax


:first-child {
  css declarations;
}

Use this code to select and style every i element of every p element, where the p element is the first child of its parent:


p:first-child i {
  background: green;
}

To select and style the first li element in lists, use this code:


li:first-child {
  background: green;
}

If you want to select and style the first child element of every ul element, use this code:


ul > :first-child {
  background: green;
}

How to select all children other than the first one?

CSS Syntax


:not(:first-child) {
  css declarations;
}

Use this code to select and style every i element other than the first child of every p element. Same example as above but with NOT first child.


p:not(:first-child) i {
  background: green;
}

To select and style all the li elements other than the first in lists, use this code:


li:not(:first-child) {
  background: green;
}

If you want to select and style all the children other than the first of every ul element, use this code:


ul > :not(:first-child) {
  background: green;
}

All modern browsers where CSS selectors level 3 are supported. More: https://www.w3.org/TR/selectors-3/

Sources: https://www.w3schools.com/cssref/sel_firstchild.asp

0 Comments

Leave a reply

Your email address will not be published. required fields are marked *