Introduction to CSS :nth-child() Selector
The :nth-child() selector in CSS is used to select elements that are the nth child of their parent. It is a pseudo-class, meaning it is used to define a special state of an element. The :nth-child() selector is particularly useful when you want to apply styles to specific items within a container, like a list or a table, without adding extra classes or ids.
The :nth-child()
selector in CSS is used to select elements that are the nth child of their parent. It is a pseudo-class, meaning it is used to define a special state of an element. The :nth-child()
selector is particularly useful when you want to apply styles to specific items within a container, like a list or a table, without adding extra classes or ids.
Basic Example with a List
Let's consider a basic unordered list (<ul>
) with several list items (<li>
):
<ul class="my-list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
Selecting a Specific Child
To select the second <li>
in our list and change its color to red, we use:
.my-list li:nth-child(2) {
color: red;
}
The second item in the list will now be red.
Odd and Even Children
We can target all odd or even items using the odd
and even
keywords:
.my-list li:nth-child(odd) {
background-color: lightgray;
}
This will apply a light gray background to the 1st, 3rd, and 5th items in the list.
Using Formulas
The an+b
formula lets us select items based on a repeating pattern:
.my-list li:nth-child(3n+1) {
font-weight: bold;
}
This formula will bold every third item, starting with the first one (1st, 4th, etc.).
Selecting a Range of Children
To highlight a range of items, say the 2nd to 4th items:
.my-list li:nth-child(n+2):nth-child(-n+4) {
border: 2px solid blue;
}
Items 2, 3, and 4 will have a blue border.
Selecting the First Few Children
To style only the first three items:
.my-list li:nth-child(-n+3) {
padding: 10px;
}
The first three items will have extra padding.
Excluding Elements with :nth-of-type()
Consider a mixed list of <span>
and <em>
elements within a <div>
:
<div class="mixed-list">
<span>Span 1</span>
<em>Em 1</em>
<span>Span 2</span>
<em>Em 2</em>
<span>Span 3</span>
</div>
To select every second <span>
:
.mixed-list span:nth-of-type(2n) {
color: purple;
}
Every second <span>
element will be purple, but <em>
elements are not affected.
Understanding the :nth-child()
Selector in Tables
Let's apply :nth-child()
to a table with <tr>
elements:
<table class="my-table">
<tr><td>Row 1, Cell 1</td><td>Row 1, Cell 2</td></tr>
<tr><td>Row 2, Cell 1</td><td>Row 2, Cell 2</td></tr>
<tr><td>Row 3, Cell 1</td><td>Row 3, Cell 2</td></tr>
</table>
To alternate row colors:
.my-table tr:nth-child(odd) {
background-color: #e0e0e0;
}
.my-table tr:nth-child(even) {
background-color: #f5f5f5;
}
Odd rows will have a light gray background, while even rows will be slightly lighter.
Conclusion
The :nth-child()
selector is a very versatile pseudo-class that can be used to target elements in a patterned and dynamic fashion. It's especially useful for lists, tables, and any repeating content where you want to apply styles to elements in a specific order. By mastering :nth-child()
, you can create more sophisticated and visually appealing designs without cluttering your HTML with extra classes or IDs.
Recommended
2m · 6min read
Web Development
2m · 6min read
Build a Real-time Speech Recognition Search Box with Next.js and Tailwind CSS
Building a real-time speech recognition search box using Next.js, Tailwind CSS, and the react-speech-recognition library
2m · 5min read
Web Development
2m · 5min read
How to Show Customized Relative Time with JavaScript
Learn how to create a JavaScript function to display relative time (like "5min ago" or "2y ago") by calculating the difference between the current date and an input date, converting it into various time units (seconds, minutes, hours, days, weeks, months, years), and returning the most appropriate unit as a string.
2m · 4min read
Web Development
2m · 4min read
How to Use Middleware in Next.js 14 for Route Protection
Implement middleware in Next.js 14 to protect routes, manage user authentication, handle role-based access. Middleware allows you to protect sensitive areas, such as user dashboards, while keeping public pages accessible to everyone.
2m · 5min read
Web Development
2m · 5min read
State Context vs Redux in React.js: When to Use Each One?
Learn the key differences between React's Context API and Redux for effective state management in your React.js applications, and discover which solution suits your project best.
2m · 4min read
Web Development
2m · 4min read
Build a Reusable Navbar Component for Multiple Pages Using HTML, CSS, and JavaScript
In this tutorial, we learned how to create a reusable navbar component using HTML, CSS, and JavaScript by dynamically loading the navbar into multiple pages, ensuring consistency and simplifying maintenance across the website.
3m · 4min read
Web Development
3m · 4min read
How to Integrate Dark Mode and Light Mode Toggle in Next.js with Tailwind CSS
Implement dynamic dark mode and light mode in Next.js with Tailwind CSS to improve user experience, accessibility, and visual customization.
4m · 6min read
Web Development
4m · 6min read
Cross-Origin Resource Sharing (CORS): How To Fix CORS
Cross-Origin Resource Sharing (CORS) is a browser mechanism that enables controlled access to resources from different domains, extending the same-origin policy while providing potential for cross-domain attacks if improperly configured.
4m · 5min read
Web Development
4m · 5min read
TypeScript Types vs Interfaces
Types vs Interfaces: Types in TypeScript are more flexible and can define a wider range of data types, including primitives, unions, intersections, tuples, and more, while interfaces are primarily used to describe the shape of objects and support declaration merging and extending, making them ideal for object-oriented programming and complex data structures
5m · 3min read
Web Development
5m · 3min read
The this Keyword in JavaScript
The this keyword in JavaScript is a reference to the object that a function is a property of. It's a fundamental concept in JavaScript, especially in object-oriented programming. Unlike in languages like Java, C#, or PHP, where this typically refers to the current instance of the class, JavaScript's this behaves differently and can be quite versatile.
6m · 8min read
Web Development
6m · 8min read
30 Common CSS Mistakes
30 CSS common mistakes we make includes: complicating selectors,Overuse of the “!important” declaration, Mishandling the z-index property, Duplicating code, Relying solely on color names and more