Similar Post: How To Apply Style Only To First Child And/Or Only To Children Other Than The First Child?

We can use different selectors in CSS to style specific child elements.

Apply style to the first child element


li:first-child {
  background: green;
}

Apply style to the last child element


li:last-child {
    background: green;
}

Apply style to the second last child element


li:nth-last-child(2) {
    background: green;
}

Apply style to nth child element


// 2nd child

p:nth-child(2) {
  background: red;
}

// 4th child 

p:nth-child(4) {
  background: red;
}

Apply style to all child elements other than the first one


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

Apply style to all child elements other than the first two


li:nth-child(n+2) {
    background: green;   
}

Apply style to all odd child elements


li:nth-child(odd) {
    background: green;   
}

 Apply style to all even child elements


li:nth-child(even) {
    background: green;   
}

Apply style to first two child elements


li:nth-child(-n+2) {
    background: green;   
}

Apply style to all but skip the first two child elements


li:nth-child(n+2) {
    background: green;   
}

0 Comments

Leave a reply

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