HTML: The strong and em tags

Псевдоклассы группы 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. Часто не получается сразу в уме составить правильную формулу.

Источник

CSS Child Selector

CSS-Child-Selector

CSS child Selector is defined as the CSS selector that selects only elements that are direct children which is clearer than the contextual selector. This selector uses greater than the symbol “>” that appears between two different selectors, and it is more specific than the descendant selector, which helps to simplify the CSS Style code. The second selector should be the immediate children of the elements.

Web development, programming languages, Software testing & others

Element1 is the parent, and element2 is the child selector.

How does Child Selector work in CSS?

The working process is very simple. This child selector has two selectors to work with and is separated by the “ > ” symbol. The first selector says that it is a parent element, and the second selector says it is a child element with the style properties.

Here let’s take a sample tree structure for a given HTML document.

tree-structure

For example, if an HTML code is like In the above diagram, every element is either a parent or child, forming a parent-child relationship. The root element here is the body element has two children, the p and ul elements. So here, the p element has only one parent, which may have many children, em and strong, respectively. To select p, we need to give a rule like body > p. Suppose we are in need to select an ‘A ‘element using a selector. We would give a rule like strong > A, which is something like p> a; it is not possible using child selectors.

So in the above sample code, the element is the parent followed by a child element

. So the above statement rule makes any paragraph with the size 12px.

Examples to Implement CSS Child Selector

In this section, we shall explore the child selector briefly with examples. So let’s get started.

Example #1

    div > p  

This paragraph is under the div element

This paragraph2 is under the div element.

This paragraph is not under the div element. As it is not the child element of div

Even This paragraph is under the div element.

This paragraph is not under the div element.

This paragraph is not under the div element.

Explanation: Here, we use div > p selector, which says that div is a parent and it selects the child element p, which is the child elements. So over here, the child elements are highlighted in color. The child selector for the above code would look like this.

CSS Child Selector - 1

Example #2

CSS Child Selector - 2

Example #3

Targeting Bold element using child selector

  div.select > b  
Content 1
Content 2
Content 3
Last content.

Explanation: The above code says the child selector selects the div class followed by element. Therefore the first b element content and last b element are stylish.

Example #4

  1. The List content given here is blue.
  • Over here, the text context is not styled in this list .
    1. As the element is not Child .

CSS Child Selector - 4

For the same html Code above. Let’s see a different selection of the child elements.

body > div > ul Output:

html Code

Now you can see the style changes in the second line as I have made a child selector deep down.

Example #5

    body > p > a 

From the World Health Organization

This pandemic disease COVID-19 is an infectious disease which makes breathing illness. It gets spreaded when an Infected person sneeze or cough. And all the public health and other social measures have taken risky work in their work-place is the foundation of The recovery time for this dangerous disease is unknown.

Further reading more here

style changes

Example #6

Child selector demo using Span and div element

  span < background-color: #00FFFF; >div > span 
This is the first Span Content under div element. Second Span under the div element.
This content of the span is not included under div.

using Span

Conclusion

Therefore, this article explained how to use the CSS Child selector with their syntax and examples. With this child selector, we could build powerful websites that could be challenging and worthful. Also, we had the right overview of what a child selector is and how to use them in real cases.

This is a guide to CSS Child Selector. Here we discuss an introduction to CSS Child Selector, its syntax, and how it works with examples. You can also go through our other related articles to learn more –

38+ Hours of HD Videos
9 Courses
5 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

149+ Hours of HD Videos
28 Courses
5 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

253+ Hours of HD Videos
51 Courses
6 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

CSS Course Bundle — 19 Courses in 1 | 3 Mock Tests
82+ Hours of HD Videos
19 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

Источник

Читайте также:  Плавное переливание цветов css
Оцените статью