CSS Pseudo Selector (:nth-child) - Best Practices
CSS Pseudo Selector (:nth-child) - Best Practices.
When I was trolling on the internet - I found another awe-inspiring thing you can do with the :nth-child
selector. This is so awesome because these tricks almost do JavaScript works. Before I unveil these tricks - Let’s Discuss the CSS Pseudo Selector itself.
What's a CSS Pseudo-Classes
A CSS pseudo-selectors are keywords added to specific elements to select and define the state of the element(s). The CSS Pseudo class falls under the CSS Selector, categorized in two phases: Pseudo Class and Pseudo element. Perhaps the CSS Pseudo Selector is different from CSS Pseudo Element. For details, see the difference here.
Syntax
Selector:pseudo-class{ property: value; }
We know the :nth-child is used to select an element with its index - examples of the common way use use it are.
Example 1
Selecting a single element - We are selecting the third
li{ background:#222; } li:nth-child(3){ background:#37a000; }
Example 2
If we have to select the fifth li
The Code
li{ background:#222;` }
li:nth-child(5){ background:#37a000` }
The New Tricks I Found
What if you want to perform a loop operation whereby you need to select the first three li ‘s - The trick was inspired by the question that first came through my mind is - Can I loop with CSS only ? Yes, we can loop to perform different tasks.
Example 1
We will be selecting the first three li’s and we are going to style it with a single line of code.
The Code
li{ background:#222; }
li:nth-child(-n+3){` background:#37a000 }
Code Explained
- The minus size means that you want to style in descending other
n : This represent the index number
+3 This represent that you want to select from index of 3
Please note that there are no spaces between the values in the parenthesis, adding spaces will not make it work.
Example 2
We will be selecting the last three li’s and we are going to style it with a single line of code. The syntax is a bit different:
The Code
li{ background:#222; }
li:nth-child(n+4){ `background:#37a000` }
Code Explained
- The minus size means that you want to style in descending other
n : This represent the index number
+4 This represent that you want to select from index of 3
Hello friend congratulations I liked your post the truth, I learned with your post about that selector thanks :)
@AlexanderGDevel Okay, I appreciate this. Please share with others.
WEQDWD