Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

CSS Basic

CSS :nth-child() Selector

Posted in CSS Tutorial
Updated on Oct 27, 2024
By Mari Selvan
👁️ 24 - Views
⏳ 4 mins
💬 1 Comment
CSS :nth-child() Selector

Photo Credit to CodeToFun

🙋 Introduction

The :nth-child() selector in CSS allows you to target elements based on their position within a parent element.

This pseudo-class is extremely flexible, letting you style elements based on patterns or specific positions.

Whether you're working with tables, lists, or any repeated HTML structure, the :nth-child() selector can be a powerful tool to apply styles dynamically.

💡 Syntax

The signature of the :nth-child() Selector is as follows:

Syntax
Copied
Copy To Clipboard
element:nth-child(n) {
    /* CSS properties */
}
  • element refers to the element you want to style.
  • n can be a number, keyword, or formula that determines which elements to select.

📝 Example Syntax

  • :nth-child(2): targets the second child.
  • :nth-child(odd): targets all odd-numbered children.
  • :nth-child(3n+1): targets every third child, starting from the first one.

📝 Example

Here is an example of how to use the :nth-child() selector in CSS:

☠️ HTML

HTML
Copied
Copy To Clipboard
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS :nth-child() Selector Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
        <li>Item 5</li>
    </ul>
</body>
</html>

🎨 CSS

CSS
Copied
Copy To Clipboard
/* Style every second list item */
li:nth-child(2n) {
    background-color: lightblue;
}

/* Style the third list item */
li:nth-child(3) {
    font-weight: bold;
    color: red;
}

In this example:

  • Every second <li> element has a light blue background.
  • The third <li> element is styled with bold red text.

Keywords for nth-child()

  • odd: Targets odd-numbered elements (1, 3, 5, 7, …).
  • even: Targets even-numbered elements (2, 4, 6, 8, …).

Using Formulas in nth-child()

The formula an + b helps you create more complex patterns for selecting child elements:

  • n is a counter starting from 0, increasing by 1 for each child.
  • a represents the step size (how often to select an element).
  • b represents the starting point in the sequence.

Example with Formula:

CSS
Copied
Copy To Clipboard
/* Select every 3rd item starting from the first one */
li:nth-child(3n+1) {
    background-color: lightgreen;
}

💬 Usage Tips

  • You can combine :nth-child() with other selectors to target specific elements. For instance, p:nth-child(2) targets the second <p> tag inside a parent.
  • Unlike the :nth-of-type() selector, :nth-child() counts all child elements, regardless of their type.

⚠️ Common Pitfalls

  • Counting Issues: The :nth-child() selector counts all children in the parent element, not just elements of the same type. For example, if you have a <div> and a <p> as siblings, both will be counted, which might lead to unexpected results.
  • Zero-based Counting: Remember that the counting starts from 1, not 0, which can sometimes cause confusion.
  • Complex Formulas: When using an + b formulas, ensure you carefully adjust the step (a) and the offset (b) to match the desired selection pattern.

🎉 Conclusion

The CSS :nth-child() selector provides a robust way to style elements based on their position within a parent container. It allows for dynamic and patterned styling that can save time and improve the maintainability of your CSS.

By mastering this selector, you can handle everything from simple styling for lists to more complex grid or table layouts with ease.

👨‍💻 Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
👋 Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy