DEV Community

Cover image for CSS nth:child selector
Shubham Tiwari
Shubham Tiwari

Posted on

CSS nth:child selector

Hello guys today i will be showing you the use of nth-child selector in CSS.

  • nth-child selector can be used to select any number of elements from a group of same type of element, or with same class, etc.
  • Example - Suppose we have 10 paragraphs created with "p" tag and we want to give every second paragraph a background color of black.So, instead of providing separate class names to all the 10 elements we can provide 1 class name to all and use that class name with nth-child to select every second paragraph in that group

Example 1 - Basic styling

.paragraph:nth-child(2n){
background-color:black;
color:white;
}
Enter fullscreen mode Exit fullscreen mode
  • It will give a background color of black and text color of white to every second paragraph in that group having the same class name "paragraph"
  • You can also select the "p" tag directly like this
p:nth-child(2n){
background-color:black;
color:white;
}
Enter fullscreen mode Exit fullscreen mode
  • It's not a recommended approach as there will be other "p" tags in the webpage and it will apply the styling to all the "p" tags.So, better go with the class name approach.

Example 2 - Using nth-child with Animation

  • You can see all the three span elements have same class name and using nth-child selector all the three span elements have different animation styling and delay.

THANK YOU FOR CHECKING THIS POST

You can contact me on -
Instagram - https://www.instagram.com/supremacism__shubh/
LinkedIn - https://www.linkedin.com/in/shubham-tiwari-b7544b193/
Email - shubhmtiwri00@gmail.com

^^You can help me by some donation at the link below Thank youπŸ‘‡πŸ‘‡ ^^
β˜• --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/js-push-and-pop-with-arrays-33a2/edit

https://dev.to/shubhamtiwari909/tostring-in-js-27b

https://dev.to/shubhamtiwari909/join-in-javascript-4050

https://dev.to/shubhamtiwari909/going-deep-in-array-sort-js-2n90

Top comments (0)