You get a bonus - 1 coin for daily activity. Now you have 1 coin

Neighbor CSS Selectors

Lecture



Neighboring elements of a web page are called when they immediately follow each other in the document code. Consider a few examples of the relationship of elements.

<p> Lorem ipsum <b> dolor </ b> sit amet. </ p>

In this example, the <b> tag is a child of the <p> tag, because it is inside this container. Accordingly, <p> acts as the parent <b>.

<p> Lorem ipsum <b> dolor </ b> <var> sit </ var> amet. </ p>

Here, the <var> and <b> tags do not overlap in any way and are adjacent elements. The fact that they are located inside the container <p> does not affect their attitude.

<p> Lorem <b> ipsum </ b> dolor sit amet, <i> consectetuer </ i> adipiscing <tt> elit </ tt>. </ p>

Nearby here are the tags <b> and <i>, as well as <i> and <tt>. At the same time, <b> and <tt> do not refer to adjacent elements due to the fact that there is a container <i> between them.

To control the style of neighboring elements, the plus symbol (+) is used, which is set between two selectors. The general syntax is as follows.

Selector 1 + Selector 2 {Description of style rules}

Spaces around the plus are not necessary, the style with such a record is applied to the Selector 2, but only if it is adjacent to the Selector 1 and immediately follows it.

Example 11.1 shows the structure of the interaction of tags with each other.

Example 11.1. Using adjacent selectors

HTML5CSS 2.1IECrOpSaFx

<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Соседние селекторы</title> <style> B + I { color: red; /* Красный цвет текста */ } </style> </head> <body> <p>Lorem <b>ipsum </b> dolor sit amet, <i>consectetuer</i> adipiscing elit.</p> <p>Lorem ipsum dolor sit amet, <i>consectetuer</i> adipiscing elit.</p> </body> </html> 

The result of the example is shown in Fig. 11.1.

  Neighbor CSS Selectors

Fig. 11.1. Highlighting text with adjacent selectors

In this example, the text color for the contents of the container <i> changes when it is located immediately after the container <b>. In the first paragraph, this situation is realized, so the word “consectetuer” in the browser is displayed in red. In the second paragraph, although the <i> tag is present, there is no <b> tag in the neighborhood, so the style does not apply to this container.

Let us consider a more practical example. Often there is a need for the text of the article to include various footnotes and notes. Usually, a new style class is created for this purpose and applied to the paragraph, this way you can easily change the appearance of the text. But we will go the other way and use the neighboring selectors. To select comments, create a new class, call it sic, and begin applying it to the <h2> tag. The first paragraph after such a title is highlighted with the background color and indent (Example 11.2). The appearance of the remaining paragraphs will remain unchanged.

Example 11.2. Change paragraph style

HTML5CSS 2.1IECrOpSaFx

 <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Изменение стиля абзаца</title> <style> H2.sic { font-size: 140%; /* Размер шрифта */ color: maroon; /* Цвет текста */ font-weight: normal; /* Нормальное начертание текста */ margin-left: 30px; /* Отступ слева */ margin-bottom: 0px; /* Отступ снизу */ } H2.sic + P { background: #ddd; /* Цвет фона */ margin-left: 30px; /* Отступ слева */ margin-top: 0.5em; /* Отступ сверху */ padding: 7px; /* Поля вокруг текста */ } </style> </head> <body> <h1>Методы ловли льва в пустыне</h1> <h2>Метод последовательного перебора</h2> <p>Пусть лев имеет габаритные размеры L x W x H, где L - длина льва от кончика носа до кисточки хвоста, W - ширина льва, а H - его высота. После чего пустыню разбиваем на ряд элементарных прямоугольников, размер которых совпадает с шириной и длиной льва. Учитывая, что лев может находиться не строго на заданном участке, а одновременно на двух из них, клетку для ловли следует делать повышенной площади, а именно 2L x 2W. Благодаря этому мы избежим ошибки, когда в клетке окажется пойманным лишь половина льва или, что хуже, только его хвост.</p> <h2 class="sic">Важное замечание</h2> <p>Для упрощения расчетов хвост в качестве погрешности измерения можно отбросить и не принимать во внимание.</p> <p>Далее последовательно накрываем каждый из размеченных прямоугольников пустыни клеткой и проверяем, пойман лев или нет. Как только лев окажется в клетке, процедура поимки считается завершенной.</p> </body> </html> 


The result of this example is shown in Fig. 11.2.

  Neighbor CSS Selectors

Fig. 11.2. Changing the paragraph view due to the use of adjacent selectors

In this example, the text is formatted using paragraphs (<p> tag), but the H2.sic + P entry only sets the style for the first paragraph after the <h2> tag, which has a class named sic added.

Neighboring selectors are convenient to use for those tags, to which indents are automatically added, in order to independently adjust the jib value. For example, if the <h1> and <h2> tags go in a row, then the distance between them is easy to adjust with the help of neighboring selectors. The situation is similar for the consecutive <h2> and <p> tags, as well as in other similar cases. In Example 11.3, the amount of indentation between the specified tags is changed in this manner.

Example 11.3. Indents between headings and text

HTML5CSS 2.1IECrOpSaFx

 <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Соседние селекторы</title> <style> H1 + H2 { margin-top: -10px; /* Смещаем заголовок 2 вверх */ } H2 + P { margin-top: -1em; /* Смещаем первый абзац вверх к заголовку */ } </style> </head> <body> <h1>Заголовок 1</h1> <h2>Заголовок 2</h2> <p>Абзац!</p> </body> </html> 

Since, when using neighboring selectors, the style is applied only to the second element, the size of the indents is reduced due to the inclusion of a negative value for the margin-top property. This text goes up, closer to the previous element.

Questions to check

1. What tags in this code are adjacent?

<p> <b> Formula of sulfuric acid: </ b> <i> H <sub> <small> 2 </ small> </ sub> SO <sub> <small> 4 </ small> </ sub> < / i> </ p>

  1. <P> and <i>
  2. <B> and <i>
  3. <I> and <sub>
  4. <SUB> and <SMALL>
  5. <I> and <SMALL>

2. The following HTML code is available :

<p> <b> The Great Fermat Theorem </ b> </ p>
<p> <i> X <sup> <small> n </ small> </ sup> + Y <sup> <small> n </ small> </ sup>
= Z <sup> <small> n </ small> </ sup> </ i> </ p>
<p> where n is an integer> 2 </ p>

Which text is highlighted in red using the style SUP + SUP {color: red; }?

  1. "X"
  2. "Y"
  3. "Z"
  4. The second "n"
  5. The second and third "n".

Answers

1. <b> and <i>

2. The second and third "n".

created: 2014-10-19
updated: 2021-03-13
285



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Cascading CSS / CSS3 Style Sheets

Terms: Cascading CSS / CSS3 Style Sheets