- CSS Child Selector Tutorial
- Child Selector in CSS
- CSS Direct Child Selector:
- Direct Child Selector in CSS Syntax:
- Example: using direct child selector in CSS
- CSS Descendant Child Selector:
- Descendant Child Selector in CSS Syntax:
- Example: using descendant child selector in CSS
- CSS Pseudo Class: first-child
- Example: using ::first-child pseudo class in CSS
- CSS Pseudo Class: last-child
- Example: using ::last-child pseudo class in CSS
- CSS Pseudo Class: only-child
- Example: using ::only-child pseudo class in CSS
- CSS Pseudo Class: nth-child()
- CSS Pseudo Class nth-child() Syntax:
- Example: using ::nth-child() pesudo class in CSS
- nth-child() Pseudo Class with “odd” and “even” values:
- Example: using “odd” and “even” values in nth-child() pseudo class
- nth-child() Pseudo Class with “xn” Values
- Example: nth-child() with “xn” values
- nth-child() Pseudo Class with “xn + numbers”
- Example: nth-child() class with “xn + numbers”
- nth-child() Pseudo Class with Negative Numbers
- Example: negative numbers and nth-child() pseudo class
- CSS Pseudo Class: first-of-type
- Example: using ::first-of-type pseudo class in CSS
- CSS Pseudo Class: last-of-type
- Example: using ::last-of-type pseudo class in CSS
- CSS Pseudo Class: nth-of-type
- Псевдоклассы группы child
- Кратко
- Пример
- Как пишется
- Подсказки
- How to Select All Child Elements Recursively in CSS
- Create HTML
- Add CSS
- Example of selecting all child elements:
- Result
- Example of selecting all child elements recursively:
CSS Child Selector Tutorial
In this section, we will learn what the child selector is and how to use it in CSS.
Child Selector in CSS
The child selectors are a set of methods we use to access one or more children of an HTML element and apply CSS styles to them.
For example, using child selectors, we can access to the first or last child of an element and format it accordingly. Or let’s say and element has both children and grandchildren, now using the child selectors, we can focus on the children of an element only (skip the grandchildren) and format them accordingly.
So in short, the child selectors are here to ease the process of accessing the children of an element and help us to apply CSS styles to them.
CSS Direct Child Selector:
The first child selector is called direct child selector and it is used to target the direct children of an HTML element.
Note that this selector won’t care about the grandchildren of the target element (basically, it will skip them).
For example, let’s say you have the element and it has 3 children. Now each of these elements also has other children for themselves as well! Now, if we use the direct child selector on the element, only the elements of the will be targeted here and so the children of these elements will be ignored.
Direct Child Selector in CSS Syntax:
`element`: this is the parent element we want to select its children.
`child-element`: this is the name of those direct children of an element we want to style using CSS. For example, if the value here is set to `.cla` then the selector will target all the direct children of the parent element that has the class name `cla` assigned to them.
Example: using direct child selector in CSS
CSS Descendant Child Selector:
This type of selector targets the children and the grandchildren (all the descendant children) of an element
Descendant Child Selector in CSS Syntax:
parent-element child-element < //body. >
`parent-element`: this is the element we want to style its descendant children.
`child-element`: this is the element/s that are the descendant of the target `parent-element` and want to style them using CSS properties.
Example: using descendant child selector in CSS
CSS Pseudo Class: first-child
Using this selector, we can target the first child of an element and apply CSS styles to it.
For example, if there’s a element and its first child is the element, we can use this selector to target that element and style it accordingly.
This is the syntax of this selector:
Here, the element-name is the one we want to access its first child and change its styles.
Example: using ::first-child pseudo class in CSS
CSS Pseudo Class: last-child
This type of selector is used to access the last child of an element and style that using CSS properties.
This is the syntax of this selector:
The `element-name` here is the name of the target element we want to style its last child.
Example: using ::last-child pseudo class in CSS
CSS Pseudo Class: only-child
When we want to apply a style to an element that is the only child of its parent, we can use this type of selector.
Example: using ::only-child pseudo class in CSS
CSS Pseudo Class: nth-child()
When we want to apply a style to an element that is the nth child of its parent, we can use this type of selector
CSS Pseudo Class nth-child() Syntax:
element-name:nth-child(number)< //body… >
Here the `element-name` is the name of the element we want to target one of its children and style it.
`:nth-child(number)`: The number we set in the pair of parentheses defines the child element we want to style. For example, if the value is set to 3, that means the third child of the target element is the target of this selector then.
Here, the target element we want to style is the third child of an element that has the id value of #purp.
Example: using ::nth-child() pesudo class in CSS
nth-child() Pseudo Class with “odd” and “even” values:
There are two special words we can put within the pair of parentheses of the `nth-child()` selector:
- “odd”: this value means the target of the selector will be those children of an element that have an odd position. For example, the first element, the third element, the fifth element, and so on.
- “even”: this value means the target of the selector will be those children of an element that have an even position. For example, the second element, the fourth element, the sixth element, and so on.
Example: using “odd” and “even” values in nth-child() pseudo class
nth-child() Pseudo Class with “xn” Values
Using this type of selector, we can define a step and target the children of an element based on this step! For example, we can set the value to 3, which means skip 2 child elements at a time and add the next one as the target element of the selector.
Example: nth-child() with “xn” values
nth-child() Pseudo Class with “xn + numbers”
The `nth-child()` selector by default starts from the first child of an element, but we can change this position and make the selector to start from another child of an element.
This means the start position of this selector must be the third child element of the target parent element.
Example: nth-child() class with “xn + numbers”
nth-child() Pseudo Class with Negative Numbers
We can also use a negative number for ‘n’ as the value of the selector of this type.
For example, if we set the value to -3n + 5, browsers will cycle through child elements backwardly, starting from fifth child, trying to find every third element.
Example: negative numbers and nth-child() pseudo class
CSS Pseudo Class: first-of-type
If we want to format those elements that are the first type within the body of their container (parent) we can use this type of selector.
Note: We are looking for “first type” in this type of selector. So don’t confuse it with “first-child” because a first-type might be the nth child of its parent.
Here, browsers will check the entire elements of the page to see if they have a
element as their children. Now, if they found one, the first sub-element of those parent elements that are of type
, will be styled according to the declaration block of this selector.
Example: using ::first-of-type pseudo class in CSS
CSS Pseudo Class: last-of-type
If we want to format those elements that are the last type within the body of their container (parent) we can use this type of selector.
Note: We are looking for “last type” in this type of selector. So don’t confuse it with “last-child” because a last-type might be the nth child of its parent.
Here, browsers will check the entire elements of the page to see if they have a
element as their children. Now, if they found one, the last sub-element of those parent elements that is of type
, will be styled according to the declaration block of this selector.
Example: using ::last-of-type pseudo class in CSS
CSS Pseudo Class: nth-of-type
If we want to format those elements that are the nth type within the body of their container (parent) we can use this type of selector.
Here’s the syntax of this type of selector:
Псевдоклассы группы child
Группа этих псевдоклассов позволяет выбирать элементы не по классу или тегу, а по порядковому номеру.
Время чтения: меньше 5 мин
Кратко
Скопировать ссылку «Кратко» Скопировано
При помощи этих псевдоклассов можно удобно выбирать элементы по их порядковому номеру внутри родительского элемента.
Пример
Скопировать ссылку «Пример» Скопировано
Раскрасим в разные цвета фон у пунктов списка. Обратите внимание, что у всех пунктов списка одинаковые классы, а значит, мы не сможем обратиться к отдельным пунктам при помощи селектора по классу.
У всех пунктов списка будет синий фон:
.list-item background-color: #2E9AFF;>
.list-item background-color: #2E9AFF; >
У первого пункта списка (первого дочернего элемента) будет тёмно-зелёный фон:
.list-item:first-child background-color: #286C2D;>
.list-item:first-child background-color: #286C2D; >
У последнего пункта списка (последнего дочернего элемента) будет оранжевый фон:
.list-item:last-child background-color: #FF8630;>
.list-item:last-child background-color: #FF8630; >
У второго пункта списка будет зелёный фон:
.list-item:nth-child(2) background-color: #41E847;>
.list-item:nth-child(2) background-color: #41E847; >
У предпоследнего пункта списка будет розовый фон:
.list-item:nth-last-child(2) background-color: #F498AD;>
.list-item:nth-last-child(2) background-color: #F498AD; >
Как пишется
Скопировать ссылку «Как пишется» Скопировано
Есть три суперпростых по своей логике работы псевдокласса из этого набора:
- :only — child — выбирает любой элемент, который является единственным дочерним элементом своего родителя. Можно имитировать аналогичное поведение следующими комбинациями: :first — child : last — child или :nth — child ( 1 ) : nth — last — child ( 1 ) , но зачем так сложно, если можно проще?
- :first — child — выбирает первый дочерний элемент в родителе.
- :last — child — выбирает последний дочерний элемент в родителе.
Псевдоклассы, несущие в себе сочетание букв nth , работают гораздо интереснее. Для их правильной работы нужно указать в скобках паттерн, по которому будут выбираться дочерние элементы.
Звучит сложнее, чем работает. Начнём с простого, с ключевых слов:
- :nth — child ( odd ) — выбирает нечётные элементы внутри родителя, подходящие под левую часть селектора.
- :nth — child ( even ) — выбирает чётные элементы внутри родителя, подходящие под левую часть селектора.
В круглых скобках мы можем указать просто цифру. Таким образом будет выбран соответствующий этой цифре дочерний элемент. Например, :nth — child ( 3 ) выберет третий дочерний элемент, подходящий под левую часть селектора.
Но всё становится гораздо интереснее, когда мы хотим выбрать, к примеру, каждый третий элемент внутри родителя. Используем для этого формулу :nth — child ( 3n ) . Вместо n будет подставляться 0, затем 1, 2 и так далее. В результате умножения в скобки будет подставляться 0, 3, 6, 9, и так до тех пор, пока не закончатся дочерние элементы внутри родителя.
Пойдём дальше и попробуем выбрать каждый шестой элемент, начиная с десятого. Тут нам к умножению на n нужно будет прибавить ещё 10, чтобы отсчёт начался не с 0, а с 10: nth — child ( 6n+10 ) .
Псевдокласс :nth — last — child работает абсолютно аналогично, только счёт ведётся с конца.
Подсказки
Скопировать ссылку «Подсказки» Скопировано
💡 Часто начинающие разработчики пытаются применить эти псевдоклассы к родительскому элементу. Но тут необходимо просто запомнить, что нужно применять псевдоклассы именно к дочерним элементам, из списка которых надо выбрать. При расчёте порядкового номера дочернего элемента учитываются все соседние дочерние элементы, находящиеся на одном уровне с элементом, к которому мы применяем псевдокласс :nth — child , вне зависимости от класса и типа элемента.
💡 Не надо стесняться пользоваться калькулятором NTH. Часто не получается сразу в уме составить правильную формулу.
How to Select All Child Elements Recursively in CSS
A child selector matches all child elements of a specified element. It is composed of two or more selectors that are separated by «>».
A child selector has the following syntax:
This syntax selects all child elements. If you want to select child elements recursively, use the syntax below.
First, we’ll explain how to select all child elements.
Create HTML
div> span>Paragraph 1 span> span>Paragraph 2 span> p> span>Paragraph 3 span> p> div> span>Paragraph 4 span> span>Paragraph 5 span>
Add CSS
- Add the display property set to «block» for all the elements.
- Add a child selector and set the background-color property.
span < display: block; > div>span < background-color: #9ba2a3; >
Example of selecting all child elements:
html> html> head> title>Title of the document title> style> span < display: block; > div > span < background-color: #9ba2a3; > style> head> body> div> span>Paragraph 1 span> span>Paragraph 2 span> p> span>Paragraph 3 span> p> div> span>Paragraph 4 span> span>Paragraph 5 span> body> html>
Result
Now, we’ll discuss another example where we select all child elements recursively. In the following example, we use the second syntax mentioned above and add background-color to the div class. The asterisk (*) matches any element.
Example of selecting all child elements recursively:
html> html> head> title>Title of the document title> style> span < display: block; > div.example, div.example > * < background-color: #9ba2a3; > style> head> body> div class="example"> span>Paragraph 1 span> span>Paragraph 2 span> p> span>Paragraph 3 span> p> div> span>Paragraph 4 span> span>Paragraph 5 span> body> html>