- :nth-child()
- Try it
- Syntax
- Keyword values
- Functional notation
- The of syntax
- Examples
- Example selectors
- Detailed example
- HTML
- CSS
- Result
- Using ‘of ‘
- HTML
- CSS
- Result
- of selector syntax vs selector nth-child
- HTML
- CSS
- Result
- Using of selector to fix striped tables
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Псевдокласс :nth-child
- Синтаксис
- Значения
- CSS по теме
- Псевдокласс :nth-child
- Синтаксис
- Значения
- CSS по теме
:nth-child()
The :nth-child() CSS pseudo-class matches elements based on their position among a group of siblings.
Try it
Note: In the element:nth-child() syntax, the child count includes sibling children of any element type; but it is considered a match only if the element at that child position matches the other components of the selector.
Syntax
:nth-child() takes a single argument that describes a pattern for matching element indices in a list of siblings. Element indices are 1-based.
Keyword values
Represents elements whose numeric position in a series of siblings is odd: 1, 3, 5, etc.
Represents elements whose numeric position in a series of siblings is even: 2, 4, 6, etc.
Functional notation
Represents elements whose numeric position in a series of siblings matches the pattern An+B , for every positive integer or zero value of n , where:
- A is an integer step size,
- B is an integer offset,
- n is all nonnegative integers, starting from 0.
It can be read as the An+B -th element of a list. The A and B must both have values.
The of syntax
By passing a selector argument, we can select the nth element that matches that selector. For example, the following selector matches the first three list items which have a class=»important» set.
:nth-child(-n + 3 of li.important) >
This is different from moving the selector outside of the function, like:
This selector selects list items if they are among the first three children and match the selector li.important .
Examples
Example selectors
Represents the odd rows of an HTML table: 1, 3, 5, etc.
tr:nth-child(even) or tr:nth-child(2n)
Represents the even rows of an HTML table: 2, 4, 6, etc.
Represents the seventh element.
Represents elements 5 [=5×1], 10 [=5×2], 15 [=5×3], etc. The first one to be returned as a result of the formula is 0 [=5×0], resulting in a no-match, since the elements are indexed from 1, whereas n starts from 0. This may seem weird at first, but it makes more sense when the B part of the formula is >0 , like in the next example.
Represents the seventh and all following elements: 7 [=0+7], 8 [=1+7], 9 [=2+7], etc.
Represents elements 4 [=(3×0)+4], 7 [=(3×1)+4], 10 [=(3×2)+4], 13 [=(3×3)+4], etc.
Represents the first three elements. [=-0+3, -1+3, -2+3]
Represents every
element in a group of siblings. This selects the same elements as a simple p selector (although with a higher specificity).
p:nth-child(1) or p:nth-child(0n+1)
Represents every
that is the first element in a group of siblings. This is the same as the :first-child selector (and has the same specificity).
Represents the eighth through the fifteenth
elements of a group of siblings.
Detailed example
HTML
h3> code>span:nth-child(2n+1)code>, WITHOUT an code><em>code> among the child elements. h3> p>Children 1, 3, 5, and 7 are selected.p> div class="first"> span>Span 1!span> span>Span 2span> span>Span 3!span> span>Span 4span> span>Span 5!span> span>Span 6span> span>Span 7!span> div> br /> h3> code>span:nth-child(2n+1)code>, WITH an code><em>code> among the child elements. h3> p> Children 1, 5, and 7 are selected.br /> 3 is used in the counting because it is a child, but it isn't selected because it isn't a code><span>code>. p> div class="second"> span>Span!span> span>Spanspan> em>This is an `em`.em> span>Spanspan> span>Span!span> span>Spanspan> span>Span!span> span>Spanspan> div> br /> h3> code>span:nth-of-type(2n+1)code>, WITH an code><em>code> among the child elements. h3> p> Children 1, 4, 6, and 8 are selected.br /> 3 isn't used in the counting or selected because it is an code><em>code>, not a code><span>code>, and code>nth-of-typecode> only selects children of that type. The code><em>code> is completely skipped over and ignored. p> div class="third"> span>Span!span> span>Spanspan> em>This is an `em`.em> span>Span!span> span>Spanspan> span>Span!span> span>Spanspan> span>Span!span> div>
CSS
* font-family: sans-serif; > span, div em padding: 5px; border: 1px solid tomato; display: inline-block; margin-bottom: 3px; >
.first span:nth-child(2n + 1), .second span:nth-child(2n + 1), .third span:nth-of-type(2n + 1) background-color: tomato; >
Result
Using ‘of ‘
In this example there is an unordered list of names, some of them have been marked as noted using class=»noted» . These have been highlighted with a thick bottom border.
HTML
ul> li class="noted">Diegoli> li>Shilpali> li class="noted">Caterinali> li>Jaylali> li>Tyroneli> li>Ricardoli> li class="noted">Gilali> li>Siennali> li>Titilayoli> li class="noted">Lexili> li>Aylinli> li>Leoli> li>Leylali> li class="noted">Bruceli> li>Aishali> li>Veronicali> li class="noted">Kyoukoli> li>Shireenli> li>Tanyali> li class="noted">Marleneli> ul>
CSS
* font-family: sans-serif; > ul display: flex; flex-wrap: wrap; list-style: none; font-size: 1.2rem; padding-left: 0; > li margin: 0.125rem; padding: 0.25rem; > li border: 1px solid tomato; > .noted border-bottom: 5px solid tomato; >
In the following CSS we are targeting the even list items that are marked with class=»noted» .
li:nth-child(even of .noted) background-color: tomato; border-bottom-color: seagreen; >
Result
Items with class=»noted» have a thick bottom border and items 3, 10 and 17 have a solid background as they are the even list items with class=»noted» .
of selector syntax vs selector nth-child
In this example, there are two unordered lists of names. The first list shows the effect of li:nth-child(-n + 3 of .noted) and the second list shows the effect of li.noted:nth-child(-n + 3) .
HTML
ul class="one"> li class="noted">Diegoli> li>Shilpali> li class="noted">Caterinali> li>Jaylali> li>Tyroneli> li>Ricardoli> li class="noted">Gilali> li>Siennali> li>Titilayoli> li class="noted">Lexili> ul> ul class="two"> li class="noted">Diegoli> li>Shilpali> li class="noted">Caterinali> li>Jaylali> li>Tyroneli> li>Ricardoli> li class="noted">Gilali> li>Siennali> li>Titilayoli> li class="noted">Lexili> ul>
CSS
* font-family: sans-serif; > ul display: flex; flex-wrap: wrap; list-style: none; font-size: 1.2rem; padding-left: 0; > li margin: 0.125rem; padding: 0.25rem; > li border: 1px solid tomato; > .noted border-bottom: 5px solid tomato; >
ul.one > li:nth-child(-n + 3 of .noted) background-color: tomato; border-bottom-color: seagreen; > ul.two > li.noted:nth-child(-n + 3) background-color: tomato; border-bottom-color: seagreen; >
Result
The first case applies a style to the first three list items with class=»noted» whether or not they are the first three items in the list.
The second case applies a style to the items with class=»noted» if they are within the first 3 items in the list.
Using of selector to fix striped tables
A common practice for tables is to use zebra-stripes which alternates between light and dark background colors for rows, making tables easier to read and more accessible. If a row is hidden, the stripes will appear merged and alter the desired effect. In this example, you can see two tables with a hidden row. The second table handles hidden rows using of :not([hidden]) .
HTML
table class="broken"> thead> tr>th>Nameth>th>Ageth>th>Countryth>tr> thead> tbody> tr>td>Mamitianatd>td>23td>td>Madagascartd>tr> tr>td>Yukitd>td>48td>td>Japantd>tr> tr hidden>td>Tlayolotltd>td>36td>td>Mexicotd>tr> tr>td>Adilahtd>td>27td>td>Moroccotd>tr> tr>td>Vienotd>td>55td>td>Finlandtd>tr> tr>td>Ricardotd>td>66td>td>Braziltd>tr> tbody> table> table class="fixed"> thead> tr>th>Nameth>th>Ageth>th>Countryth>tr> thead> tbody> tr>td>Mamitianatd>td>23td>td>Madagascartd>tr> tr>td>Yukitd>td>48td>td>Japantd>tr> tr hidden>td>Tlayolotltd>td>36td>td>Mexicotd>tr> tr>td>Adilahtd>td>27td>td>Moroccotd>tr> tr>td>Vienotd>td>55td>td>Finlandtd>tr> tr>td>Ricardotd>td>66td>td>Braziltd>tr> tbody> table>
CSS
.wrapper display: flex; justify-content: space-around; > td padding: 0.125rem 0.5rem; >
.broken > tbody > tr:nth-child(even) background-color: silver; >
.fixed > tbody > tr:nth-child(even of :not([hidden])) background-color: silver; >
Result
In the first table this is just using :nth-child(even) the third row has the hidden attribute applied to it. So in this instance the 3rd row is not visible and the 2nd & 4th rows are counted as even, which technically they are but visually they are not.
In the second table the of syntax is used to target only the tr s that are not hidden using :nth-child(even of :not([hidden])) .
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jun 21, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
Псевдокласс :nth-child
Псевдокласс :nth-child используется для добавления стиля к элементам на основе нумерации в дереве элементов.
Синтаксис
Значения
odd Все нечетные номера элементов. even Все четные номера элементов. число Порядковый номер дочернего элемента относительно своего родителя. Нумерация начинается с 1, это будет первый элемент в списке. выражение Задается в виде an+b , где a и b целые числа, а n — счетчик, который автоматически принимает значение 0, 1, 2.
Если a равно нулю, то оно не пишется и запись сокращается до b . Если b равно нулю, то оно также не указывается и выражение записывается в форме an . a и b могут быть отрицательными числами, в этом случае знак плюс меняется на минус, например: 5n-1.
За счет использования отрицательных значений a и b некоторые результаты могут также получиться отрицательными или равными нулю. Однако на элементы оказывают влияние только положительные значения из-за того, что нумерация элементов начинается с 1.
В табл. 1 приведены некоторые возможные выражения и ключевые слова, а также указано, какие номера элементов будут задействованы.
Значение | Номера элементов | Описание |
---|---|---|
1 | 1 | Первый элемент, является синонимом псевдокласса :first-child . |
5 | 5 | Пятый элемент. |
2n | 2, 4, 6, 8, 10 | Все четные элементы, аналог значения even . |
2n+1 | 1, 3, 5, 7, 9 | Все нечетные элементы, аналог значения odd . |
3n+2 | 2, 5, 8, 11, 14 | — |
-n+3 | 3, 2, 1 | — |
5n-2 | 3, 8, 13, 18, 23 | — |
even | 2, 4, 6, 8, 10 | Все четные элементы. |
odd | 1, 3, 5, 7, 9 | Все нечетные элементы. |
HTML5 CSS3 IE Cr Op Sa Fx
2134 2135 2136 2137 2138 Нефть 16 34 62 74 57 Золото 4 69 72 56 47 Дерево 7 73 79 34 86 Камни 23 34 88 53 103
В данном примере псевдокласс :nth-child используется для изменения стиля первой строки таблицы, а также для выделения цветом всех четных строк (рис. 1).
Рис. 1. Применение псевдокласса :nth-child к строкам таблицы
CSS по теме
Псевдокласс :nth-child
Псевдокласс :nth-child используется для добавления стиля к элементам на основе нумерации в дереве элементов.
Синтаксис
Значения
odd Все нечетные номера элементов. even Все четные номера элементов. число Порядковый номер дочернего элемента относительно своего родителя. Нумерация начинается с 1, это будет первый элемент в списке. выражение Задается в виде an+b , где a и b целые числа, а n — счетчик, который автоматически принимает значение 0, 1, 2.
Если a равно нулю, то оно не пишется и запись сокращается до b . Если b равно нулю, то оно также не указывается и выражение записывается в форме an . a и b могут быть отрицательными числами, в этом случае знак плюс меняется на минус, например: 5n-1.
За счет использования отрицательных значений a и b некоторые результаты могут также получиться отрицательными или равными нулю. Однако на элементы оказывают влияние только положительные значения из-за того, что нумерация элементов начинается с 1.
В табл. 1 приведены некоторые возможные выражения и ключевые слова, а также указано, какие номера элементов будут задействованы.
Значение | Номера элементов | Описание |
---|---|---|
1 | 1 | Первый элемент, является синонимом псевдокласса :first-child . |
5 | 5 | Пятый элемент. |
2n | 2, 4, 6, 8, 10 | Все четные элементы, аналог значения even . |
2n+1 | 1, 3, 5, 7, 9 | Все нечетные элементы, аналог значения odd . |
3n+2 | 2, 5, 8, 11, 14 | — |
-n+3 | 3, 2, 1 | — |
5n-2 | 3, 8, 13, 18, 23 | — |
even | 2, 4, 6, 8, 10 | Все четные элементы. |
odd | 1, 3, 5, 7, 9 | Все нечетные элементы. |
HTML5 CSS3 IE Cr Op Sa Fx
2134 2135 2136 2137 2138 Нефть 16 34 62 74 57 Золото 4 69 72 56 47 Дерево 7 73 79 34 86 Камни 23 34 88 53 103
В данном примере псевдокласс :nth-child используется для изменения стиля первой строки таблицы, а также для выделения цветом всех четных строк (рис. 1).
Рис. 1. Применение псевдокласса :nth-child к строкам таблицы