The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →:nth-child() selects elements by their one-based position among all element children of the same parent. The most important detail is that it counts every element sibling—not just siblings of the same tag or class. Thus, p:nth-child(2) means “a p that is the second element child overall,” not necessarily “the second paragraph.”
This guide explains the An+B syntax, shows how to select ranges and repeating patterns, compares :nth-child() with :nth-of-type() and :nth-last-child(), and introduces the newer filtered form, :nth-child(... of S).
What does :nth-child() do?
:nth-child() is a structural CSS pseudo-class. It matches an element according to its position in the list of element children belonging to its parent. Positions start at 1, not 0.
li:nth-child(3) {
color: darkblue;
}
This matches an li only when that li is the third element child of its parent.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitches#1 Best Overall
The selector does not count text nodes or comments. Whitespace between elements, indentation, and HTML comments do not change the count. Other element types do count, however.
<div class="content">
<h2>Heading</h2>
<p>First paragraph</p>
<p>Second paragraph</p>
</div>
In this example, the first paragraph is the second element child overall. Therefore:
p:nth-child(2) {
/* Matches the first paragraph */
}
p:nth-child(3) {
/* Matches the second paragraph */
}
If you actually mean “the second p among the paragraphs,” use :nth-of-type(), explained below.
Basic syntax
The general syntax is:
:nth-child(<An+B>)
/* Level 4 filtered form */
:nth-child(<An+B> of <complex-selector-list>)
The argument may be:
oddoreven- A single integer, such as
1or4 - An
An+Bexpression, such as2n + 1or-n + 3
In an An+B expression, n represents the non-negative integers 0, 1, 2, 3, and so on. A controls the step size, while B provides the offset. The resulting positions are matched only when they are valid element positions, which begin at 1.
Common :nth-child() patterns
| Selector | Matches |
|---|---|
:nth-child(1) |
Exactly the first element child |
:nth-child(3) |
Exactly the third element child |
:nth-child(odd) |
Positions 1, 3, 5, 7, and so on |
:nth-child(even) |
Positions 2, 4, 6, 8, and so on |
:nth-child(2n) |
Even positions |
:nth-child(2n + 1) |
Odd positions |
:nth-child(n + 4) |
Position 4 and every position after it |
:nth-child(-n + 3) |
The first three positions |
:nth-child(3n + 2) |
Positions 2, 5, 8, 11, and so on |
Selecting one exact position
Use an integer when only one position is needed:
.menu-item:nth-child(4) {
margin-right: 0;
}
This targets an element with the menu-item class only if it is the fourth element child overall. It does not find the fourth .menu-item if other elements appear before it.
Selecting alternating children
li:nth-child(odd) {
background-color: #f7f7f7;
}
li:nth-child(even) {
background-color: #ffffff;
}
The equivalent numeric forms are 2n + 1 for odd positions and 2n for even positions.
Selecting everything from a position onward
.card:nth-child(n + 4) {
opacity: 0.8;
}
n + 4 produces positions 4, 5, 6, 7, and so on. It does not impose a final limit.
Selecting only the first few children
.card:nth-child(-n + 3) {
border-top: 2px solid steelblue;
}
The negative coefficient creates an upper bound. The expression produces 3, 2, 1 as n increases, so it matches the first three valid positions and stops there.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Selecting a range
To match positions 3 through 5, combine two :nth-child() conditions:
Rank #2
- 3 Year Replacement Warranty. Will not corrode, fade or unravel. Sterilize your keyboard or keypad daily without damaging luminescent Keyboard Keysticks. Free Mulligan. Don't like your first trial? Get a free replacement set.
- Extra Large Type. See each key and symbol in the dim light without glasses. Great for the elderly or people with poor vision.
- Fits both laptop and desktop keyboards.
- Full 200-piece multimedia set with function keys ("F" keys) for use with Spotify, Pandora, Google Play, iHeartRadio, Slacker, TuneIn, SoundCloud, Deezer. Use with MAC and PC.
- Includes a credit card sized magnifying glass. $2.98 value. Fits in a wallet or purse. Great for reading prescriptions, content tags and mobile phones.
li:nth-child(n + 3):nth-child(-n + 5) {
font-weight: 700;
}
The first condition means “3 and later.” The second means “up to 5.” Their intersection is positions 3, 4, and 5.
The most common mistake: filtering versus counting
A selector before :nth-child() filters which elements can be matched, but it does not change the sibling list used for counting.
<div class="list">
<div class="card important">A</div>
<div class="card">B</div>
<div class="card important">C</div>
<div class="card important">D</div>
</div>
Compare these selectors:
.important:nth-child(-n + 3) {
/* An important element among the first three children overall */
}
:nth-child(-n + 3 of .important) {
/* The first three .important elements */
}
The first selector counts every element child, then asks whether the matched child also has the important class. The second selector first creates a counted set containing only .important siblings, then selects the first three from that set.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
This difference matters whenever the parent contains mixed elements or when only some siblings should participate in a visual pattern.
Using the filtered of S syntax
The optional of S clause is the Selectors Level 4 form of :nth-child(). It filters the sibling list before applying the positional formula.
For example, suppose a table contains rows that may be hidden:
tr:nth-child(even of :not([hidden])) {
background-color: silver;
}
This applies the alternating style to visible rows while excluding rows with the hidden attribute from the count. Without the filter, a hidden row could occupy an even or odd position and disrupt the visible striping.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchThe same idea works with classes:
:nth-child(-n + 3 of .card) {
outline: 2px solid royalblue;
}
This means “the first three siblings matching .card.” It is different from:
.card:nth-child(-n + 3) {
outline: 2px solid royalblue;
}
That second version means “a .card that is among the first three element children overall.”
Rank #3
- 🎹 Size: Suitable for all 88/61/54/49/37 key pianos and keyboards. White key sticker 4.0cmX1.55cm(1.57”X0.61”). Black key sticker 3.9cmX0.85cm(1.54”X0.33”).
- 🎹 Durable: The letters are printed on the backside of the transparent sticker, so they can withstand constant impact of fingers, will be always legible and never fade. Waterproof, when the surface is dirty, simply wipe it with a damp cloth to clean.
- 🎹 No Glue Left: The adhesive on the backside is clean and durable, can be removed / pasted many times. Leaving no residue on piano keys, completely no harm to keyboard.
- 🎹 Good Feeling: Piano key stickers are very thin and you can barely feel them when you play the piano. The sticker has a smooth surface and no resistance, making it comfortable when practicing techniques such as portamento and arpeggios.
- 🎹 Easy to Read: The piano letters are large enough, clear, and easy to read, kids feel joyful to learn the piano and memorize note positions. Great for beginners and little masters.
Compatibility consideration
The basic :nth-child() pseudo-class is a mature, widely available CSS feature. The optional of S syntax is newer and should be evaluated separately when supporting older browsers or a controlled browser range. Check current browser-compatibility data for the exact environments your project supports rather than assuming that every Selectors Level 4 feature has the same support profile.
Selectors Level 4 is represented in the W3C publication history as a Working Draft dated January 22, 2026. That standards status applies to the specification context; it should not be read as a claim that all Level 4 selector features are equally mature or available.
:nth-child() versus :nth-of-type()
Use :nth-child() when the position among all element children matters. Use :nth-of-type() when the position among elements of one HTML type matters.
<article>
<h1>Title</h1>
<p>First paragraph</p>
<p>Second paragraph</p>
</article>
p:nth-child(2) {
/* Matches “First paragraph” */
}
p:nth-of-type(2) {
/* Matches “Second paragraph” */
}
The h1 is the first element child, so the first p is child number 2. But among p elements, the first paragraph is number 1 and the second is number 2.
A practical rule:
- “Style the third child in this component” usually suggests
:nth-child(3). - “Style the third paragraph” usually suggests
p:nth-of-type(3). - “Style the first three elements with this class” may suggest
:nth-child(-n + 3 of .class-name).
Using :nth-last-child() to count from the end
When the requirement is based on the end of the sibling list, use :nth-last-child():
li:nth-last-child(2) {
color: crimson;
}
This matches the second-to-last element child. Like :nth-child(), the backward-counting form can use an An+B expression and, where supported, an of S filter.
:nth-last-child(-n + 3 of .card) {
/* The last three .card siblings */
}
Use this when “last,” “second-to-last,” or “final three” is the actual design rule. Do not reverse the DOM merely to make a forward selector appear to work.
Practical examples
Alternating table rows
tbody tr:nth-child(even) {
background-color: #f4f4f4;
}
This styles even-numbered element children under the selected parent. If rows can be hidden and the visible alternation must remain continuous, use the filtered version:
tbody tr:nth-child(even of :not([hidden])) {
background-color: #f4f4f4;
}
Decorating every third grid item
.grid-item:nth-child(3n + 1) {
border-left: 3px solid #2878c8;
}
This matches positions 1, 4, 7, 10, and so on. It is useful when the markup order and grid rhythm are stable. Responsive layouts can change the visual arrangement without changing DOM order, so verify that the positional rule still describes the intended design at each layout width.
Rank #4
- 【COMPATIBILITY】This keyboard stickers are designed for almost Notebooks keyboard, desktops keybard, laptops keyboard, wired keyboard, wireless keyboard.
- 【HIGH QUALITY】Made of durable non-transparent vinyl material with high hardness matte surface coating, provides a pleasant touching and typing experience.
- 【EASY FOR STUDY & COMMUNICATE】The keyboard replacement stickers can make it easier for you to study and communicate, you can switch to another language at will without changing your computer keyboard.
- 【RENEW YOUR KEYBOARD】This is the easiest and cheapest way to update your computer keyboard and make your keyboard as good as new. Special gift for children, friends, students
- 【PRODUCT DIMENSIONS】Full Size: 7.09" x 2.56" (180mm x 65mm) Each Units Size: 0.51" x 0.43" (11mm x 13mm)
Styling an initial group
.feature:nth-child(-n + 3) {
box-shadow: 0 0 0 2px gold;
}
This works when the features are the first three element children. If unrelated elements may be inserted among them, prefer:
:nth-child(-n + 3 of .feature) {
box-shadow: 0 0 0 2px gold;
}
Combining a class with a positional rule
button.primary:nth-child(2) {
font-weight: 700;
}
This requires the element to be a button, have the primary class, and be the second element child. It does not select the second primary button unless the second primary button also happens to be the second child overall.
Specificity of :nth-child()
The basic :nth-child() pseudo-class contributes the specificity of one pseudo-class. In the filtered form, the selector list after of also contributes the specificity of its most specific complex selector.
For example:
:nth-child(even of .item) {
background: #eee;
}
The selector includes the pseudo-class plus the specificity contributed by .item. This specificity behavior is defined separately from simply placing the class selector outside the pseudo-class, even in cases where the practical result may appear similar.
If a rule is difficult to override, prefer a clear component class or a deliberately managed cascade rather than adding increasingly complicated positional selectors.
Free tools Windows power users keep installed
One-click scans. No signup required.
Debugging a selector that matches the wrong element
- Inspect the parent. Confirm which element is actually the parent of the target.
- List every element child. Include headings, wrappers, buttons, icons, and other element types. Ignore text nodes and comments.
- Number the children from 1. Do not begin at zero.
- Evaluate the formula. Write out the first few positions produced by the
An+Bexpression. - Check whether you meant a restricted set. Compare
:nth-of-type()or:nth-child(... of S). - Inspect conditional markup. Ads, accessibility wrappers, empty-state elements, and server-rendered or responsive elements can change DOM order.
For example, if p:nth-child(2) unexpectedly fails, look for an element such as a heading, label, wrapper, or image before the paragraph. If the requirement is “second paragraph,” change the selector to p:nth-of-type(2).
Maintainability and accessibility
Positional selectors style based on DOM order. They do not change semantic order, keyboard navigation order, or how assistive technology interprets the document.
That makes them appropriate for genuinely positional presentation rules—such as alternating rows or a repeating grid rhythm—but less suitable for communicating that one item is important, selected, required, or otherwise semantically different.
For a meaningful state, use an explicit class or state attribute:
Recommended Free Tools
Best Value
- 💻 ✔️ EVERY ESSENTIAL SHORTCUT - With the SYNERLOGIC Reference Keyboard Shortcut Sticker, you have the most important shortcuts conveniently placed right in front of you. Easily learn new shortcuts and always be able to quickly lookup commands without the need to “Google” it.
- 💻✔️ Work FASTER and SMARTER - Quick tips at your fingertips! This tool makes it easy to learn how to use your computer much faster and makes your workflow increase exponentially. It’s perfect for any age or skill level, students or seniors, at home, or in the office.
- 💻 ✔️ New adhesive – stronger hold. It may leave a light residue when removed, but this wipes off easily with a soft cloth and warm, soapy water. Fewer air bubbles – for the smoothest finish, don’t peel off the entire backing at once. Instead, fold back a small section, line it up, and press gradually as you peel more. The “peel-and-stick-all-at-once” method only works for thin decals, not for stickers like ours.
- 💻 ✔️ Compatible and fits any brand laptop or desktop running Windows 10 or 11 Operating System.
- 💻 ✔️ Original Design and Production by Synerlogic Electronics, San Diego, CA, Boca Raton, FL and Bay City, MI, United States 2020. All rights reserved, any commercial reproduction without permission is punishable by all applicable laws.
.product-card.is-featured {
border: 2px solid gold;
}
This remains understandable if content is reordered. By contrast, a rule such as .product-card:nth-child(1) silently changes meaning when a new card is inserted before it.
Likewise, do not use :nth-child() as the only way to communicate an important status. Pair visual styling with appropriate semantic HTML and state information.
Optional further reading
If you are learning An+B expressions alongside :nth-child(), :nth-last-child(), and :nth-of-type(), a dedicated CSS selectors reference book can be a useful offline supplement. It is not required—these selectors are built into CSS—but a good reference can place the formulas and related structural selectors in one searchable resource.
Quick decision guide
| Requirement | Good starting point |
|---|---|
| The third element child, regardless of type | :nth-child(3) |
| Every other element child | :nth-child(odd) or :nth-child(even) |
| The third element of a particular type | p:nth-of-type(3) |
| The first three matching siblings | :nth-child(-n + 3 of .item) |
| Children 4 through 8 overall | :nth-child(n + 4):nth-child(-n + 8) |
| The second-to-last element child | :nth-last-child(2) |
| A semantic state such as “featured” | An explicit class or attribute, not position alone |
Frequently Asked Questions
Does :nth-child(2) select the second paragraph?
Not necessarily. It selects an element that is the second element child overall. Use p:nth-of-type(2) when you mean the second p among its paragraph siblings.
Does CSS :nth-child() count text nodes or whitespace?
No. It counts element children. Comments and text nodes, including whitespace between tags, do not affect the position.
What is the difference between .item:nth-child(2) and :nth-child(2 of .item)?
.item:nth-child(2) selects an .item only if it is the second element child overall. :nth-child(2 of .item) selects the second sibling that matches .item.
How do I select the first three children with :nth-child()?
Use :nth-child(-n + 3) for the first three element children overall. If only elements matching a selector should be counted, use :nth-child(-n + 3 of .item) where support for the filtered syntax is appropriate.
Should I use a class instead of :nth-child()?
Use a class or state attribute when the styling represents meaning—such as featured, selected, or required. Use :nth-child() for rules that are genuinely based on position, such as alternating rows.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →The Bottom Line
:nth-child() counts element siblings from 1, and it counts every element type by default. Learn to read An+B, distinguish overall-child counting from filtered counting, and choose :nth-of-type() or the filtered of S form when the requirement concerns a narrower set. For semantic states, prefer explicit classes or attributes so the styling survives changes to the markup.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

