CSS nth selector
The CSS :nth-child()
selector is a powerful pseudo-class that allows you to select elements based on their position within a parent element. It helps you target specific child elements based on their index or a formula involving the index.
The :nth-child()
selector has the following syntax:
selector:nth-child(an+b)
selector
: Represents the HTML element or class to which the:nth-child()
selector will be applied.a
andb
: Are integers or expressions that define the pattern of elements you want to select.
There are different ways to use the :nth-child()
selector:
- Selecting a specific child element:
ul li:nth-child(3) {
/* Styles for the 3rd list item in a <ul> element */
}
- Selecting a range of child elements:
ul li:nth-child(n+3):nth-child(-n+7) {
/* Styles for the 3rd to 7th list items in a <ul> element */
}
- Selecting odd or even child elements:
ul li:nth-child(odd) {
/* Styles for odd-numbered list items in a <ul> element */
}
ul li:nth-child(even) {
/* Styles for even-numbered list items in a <ul> element */
}
- Using a formula with
an+b
:
ul li:nth-child(3n+1) {
/* Styles for every 3rd list item, starting from the 1st in a <ul> element */
}
- Selecting elements based on their position relative to other elements:
ul li:nth-child(2n+1):nth-last-child(3) {
/* Styles for every 2nd list item counting from the start, and also the 3rd list item counting from the end, in a <ul> element */
}
The :nth-child()
selector can be very useful for styling or targeting specific elements in dynamic layouts, such as lists, grids, or galleries. It allows you to create complex patterns and apply different styles to various elements based on their position in the parent container.
Keep in mind that the :nth-child()
selector is 1-indexed, meaning it counts elements starting from 1, not 0. It’s also important to consider browser support, as some older versions of Internet Explorer may have limited or partial support for this selector. Always test your styles across different browsers to ensure consistent behavior.