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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to create a simple digital clock using JavaScript?JavaScriptWP_Query Class in WordPressWordPressWordPress: How to get ACF field values from another post?WordPressHow to disable scrolling on html body on menu click using JavaScript?JavaScriptRecursion in JavaScriptJavaScriptHow does while loop work in SCSS?SCSS