Pseudo-Classes/Elements
CSS :nth-child
Selecting Elements with nth-child
CSS :nth-child selects elements by position, including odd or even.
Introduction to :nth-child
The :nth-child
pseudo-class in CSS allows you to select one or more elements based on their position within a parent element. This powerful selector can be used to apply styles to elements at specific intervals, such as every other element or every third element.
Basic Syntax of :nth-child
The basic syntax of the :nth-child
pseudo-class is as follows:
element:nth-child(n)
Here, n
can be a number, keyword, or a formula. The element is selected if it is the nth child of its parent.
Using Numbers with :nth-child
By using a number, you can select a specific child element. For example, to style the third <li>
in a list:
Using Keywords: odd and even
The :nth-child
pseudo-class can use the keywords odd
or even
to select elements in those positions. This is particularly useful for styling alternating rows in tables or lists:
Using Formulas with :nth-child
The :nth-child
pseudo-class supports the use of formulas to select elements at regular intervals. The formula takes the form an + b
, where a
and b
are integers. This can be used to select every nth element:
Practical Examples
Here are some practical examples of using :nth-child
:
- Highlighting the first and every fourth item in a list:
- Styling the second and every third paragraph in a section:
Conclusion
The :nth-child
pseudo-class is a versatile tool in CSS that enables designers to apply styles based on the position of elements within a parent. Whether you're styling every other row in a table or creating complex patterns, :nth-child
provides the flexibility needed for dynamic styling.