UGURUS offers elite coaching and mentorship for agency owners looking to grow. Start with the free Agency Accelerator today.
The :nth-child
selector allows you to select one or more elements based on their source order, according to a formula.
/* Select the first list item */
li:nth-child(1) { }
/* Select the 5th list item */
li:nth-child(5) { }
/* Select every other list item starting with first */
li:nth-child(odd) { }
/* Select every 3rd list item starting with first */
li:nth-child(3n - 2) { }
/* Select every 3rd list item starting with 2nd */
li:nth-child(3n - 1) { }
/* Select every 3rd child item, as long as it has class "el" */
.el:nth-child(3n) { }
It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.
Suppose we are building a CSS grid, and want to remove the margin on every fourth grid module. Here’s that HTML:
<section class="grid">
<article class="module">One</article>
<article class="module">Two</article>
<article class="module">Three</article>
<article class="module">Four</article>
<article class="module">Five</article>
</section>
Rather than adding a class to every fourth item (e.g. .last
), we can use :nth-child
:
.module:nth-child(4n) {
margin-right: 0;
}
The :nth-child
selector takes an argument: this can be a single integer, the keywords even
, odd
, or a formula. If an integer is specified only one element is selected—but the keywords or a formula will iterate through all the children of the parent element and select matching elements — similar to navigating items in a JavaScript array. Keywords “even” and “odd” are straightforward (2, 4, 6, etc. or 1, 3, 5 respectively). The formula is constructed using the syntax an+b
, where:
- “a” is an integer value
- “n” is the literal letter “n”
- “+” is an operator and may be either “+” or “-”
- “b” is an integer and is required if an operator is included in the formula
It is important to note that this formula is an equation, and iterates through each sibling element, determining which will be selected. The “n” part of the formula, if included, represents a set of increasing positive integers (just like iterating through an array). In our above example, we selected every fourth element with the formula 4n
, which worked because every time an element was checked, “n” increased by one (4×0, 4×1, 4×2, 4×3, etc). If an element’s order matches the result of the equation, it gets selected (4, 8, 12, etc). For a more in-depth explanation of the math involved, please read this article.
To illustrate further, here are some examples of valid :nth-child
selectors:
Luckily, you don’t always have to do the math yourself—there are several :nth-child
testers and generators out there:
:nth-child(an + b of <selector>)
There is a little-known filter that can be added to :nth-child
according to the CSS Selectors specification: The ability to select the :nth-child
of a subset of elements, using the of
format. Suppose you have a list of mixed content: Some have the class .video
, some have the class .picture
, and you want to select the first 3 pictures. You could do so with the “of” filter like so:
:nth-child(-n+3 of .picture) {
/*
Selects the first 3 elements
applied not to ALL children but
only to those matching .picture
*/
}
Note that this is distinct from appending a selector directly to the :nth-child
selector:
.picture:nth-child(-n+3) {
/*
Not the same!
This applies to elements matching .picture
which _also_ match :nth-child(-n+3)
*/
}
This can get a little confusing, so an example might help illustrate the difference:
Browser support for the “of” filter is very limited: As of this writing, only Safari supported the syntax. To check the status of your favorite browser, here are open issues related to :nth-child(an+b of s)
:
Points of Interest
:nth-child
iterates through elements starting from the top of the source order. The only difference between it and:nth-last-child
is that the latter iterates through elements starting from the bottom of the source order.- The syntax for selecting the first
n
number of elements is a bit counter-intuitive. You start with-n
, plus the positive number of elements you want to select. For example,li:nth-child(-n+3)
will select the first 3li
elements. - The
:nth-child
selector is very similar to:nth-of-type
but with one critical difference: it is less specific. In our example above they would produce the same result because we are iterating over only.module
elements, but if we were iterating over a more complex group of siblings,:nth-child
would try to match all siblings, not only siblings of the same element type. This reveals the power of:nth-child
—it can select any sibling element in an arrangement, not only elements that are specified before the colon.
Related Properties
Other Resources
Browser Support
Chrome | Safari | Firefox | Opera | IE | Android | iOS |
---|---|---|---|---|---|---|
Any | 3.2+ | Any | 9.5+ | 9+ | Any | Any |
:nth-child
was introduced in CSS Selectors Module 3, which means old versions of browsers do not support it. However, modern browser support is impeccable, and the new pseudo-selectors are widely used in production environments. If you require older browser support, either polyfill for IE, or use these selectors in non-critical ways á la progressive enhancement, which is recommended.
So I have an accordion setup for my FAQ section. Inside one of the ‘accordions’ I have a form with an ul. The ul has 5 li.
What I want is to make a submit button appear when the checkbox in each li has been checked.
Is the :nth-child what I want to use for this or is there something else.
Thank you for any help you can give.
I think about javascript
it works thanks :)
Nice. Thank you for the clear write-up :-)
Thank you for the concise explanation of the nth-child pseudo-class. Very helpful- it clears up a lot about this powerful selector. I’m comfortable enough with it now to start using it.
Hi Experts,
I am trying to write a piece of CSS code to format the table in SAP Design Studio tool. In one of the table i have a CSS to hover the specific column of the table based on the n-th child selector. Below is the snippet.
.Table1 .sapzencrosstab-RowHeaderArea:hover tr > td:nth-child(4)
{
text-decoration: underline !important;
cursor: pointer !important;
}
Is it possible to mention the name of the column header here instead of fixing it as the 4th column. The requirement is to hover the column name called, say ‘Region’, instead of saying it as 4th column because Region dimension can change its position in the table when the user drills down few other dimensions into the table.
I have searched in forum to find out the css classes and possible workarounds, but could not find any.
Thanks & Regards,
Kesavan.
Hi,
The Phrase ” But the keywords or a formula will iterate through all the children of the parent element and select matching elements ”
is this also right as per my understanding -> ” But the keywords or formula goes down to every child element of the parent and select matching elements”
instead of using iterate through can it also be explained like above, is that also right according to my understanding?
How can I select specific number of last child using CSS?
For example, there are total 12 elements. I want to apply my style only on last n (1, 2, 3…) numbers of child of total 12 elements; how can I do this?
This works great if all the children are of the same type (element, class…):
.parent>.child:nth-last-child(-n+3) { /* selected last three elements with class=”child” that are direct children of elements with class=”parent” */ } or just
.child:nth-last-child(-n+3) { /* selected last three children with class=”child” */ }
Problem is when there are different children, and you only want to select last few of a subgroup of them with the same class.
This
:nth-last-child(-n+3 of selector)
let’s you select even by class, but sadly it isn’t supported anywhere but in Safari.I’m not sure how to do it for .class for all browsers, but I tend to solve this with element tags if posssible:
Subtitle
Text1
Text2
Text3
Text4
Made by
.parent>section:nth-last-of-type(-n+3) { /* select last three section elements that are direct children of elements with class=”parent” */ } (stupid example, I know..)
hi, i’m trying to place some divs after ever X amount of P, can I use this to do that. I have this which sort of works, but it puts some “random” Advertisement header in funny places and it doesnt seem to place the items in the order i put them (1,2,3,4), $(document).ready(function(){
$(‘
Advertisement
‘).insertAfter(‘#mvp-content-main p:nth-child(2)’);
$(‘
Advertisement
‘).insertAfter(‘#mvp-content-main p:nth-child(5)’);
$(‘
Advertisement
‘).insertAfter(‘#mvp-content-main p:nth-child(10)’);
$(‘
Advertisement
‘).insertAfter(‘#mvp-content-main p:nth-child(18)’);
Hello,
Thanks for a great article…
I am trying to figure out of if there is a formula, that would focus on one column independent of all other columns or rows, for example, using the grid analogy, the first cell in a grid could be given a different width to the other cells?
Thanks.
I would like to know if there is a way i can target the 2nd class, when there are 2 classes of the same name.
I have 2 instances of media-link contained withing a DIV called item. I need to basically add additional styles to the 2nd instance of the class. However this is where the difficulty comes in… I can not add any additional code, or classes to the code! I know, not ideal but its down to the solution being used, not personal choice.
Example code:
Author: John Smith
How i can controll the font color when i’m setting this css?
Given all the unanswered questions here — and me wanting to post yet another question — maybe add a link here to slackexchange or a separate forum as the questions get lost when after the posts? idk. Just thinking. But not going to post my question!! lol
It would be nice to mention if the index of the first element is 0 or 1. I don’t use these selectors every day and, every time I have to use them, I look for that information, including here. Thanks!
It’s 1
so what if you have to select the but within a particular limit for example from element 5 to element 10?? then how can you do it?
Are display:none elements, selectable with this selector?
Is there any way to select 3 to last element?