Yogesh Chauhan's Blog

How to apply style to a specific child element using CSS?

in CSS on October 15, 2020

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;   
}

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to Commit and Rollback Changes in SQL?SQL/MySQLsubstring() Method in JavaScriptJavaScriptThe Difference Between Arrays and Objects in JavaScriptJavaScriptAvoid using new Array() in JavaScriptJavaScriptWhat does useEffect do in React?ReactWhat is Host Hardening and What are some Important Hardening Steps?Miscellaneous