Adjacent selector in CSS
The adjacent selector + allows you to select an element by its adjacent neighbor above.
Example
Let's look at all the p tags immediately after the h2 tags and color them red:
html<h2>text</h2>
<p>
+
</p>
<p>
-
</p>
<p>
-
</p>cssh2 + p {
color: red;
}
Результат:
Example
Let's target all p tags immediately after elements with class .test and color them red:
html<p class="test">
text
</p>
<p>
+
</p>
<p>
-
</p>css.test + p {
color: red;
}
Результат:
Example
Let's target all elements with class .elem immediately after elements with class .test and color them red:
html<p class="test">
text
</p>
<p class="elem">
+
</p>
<p>
-
</p>css.test + .elem {
color: red;
}
Результат:
Practical tasks
Задание 1
Given code:
html<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li id="elem">5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
</ul>
Write a selector that will select the element immediately after the element #elem.
Задание 2
Given code:
html<ul>
<li>1</li>
<li class="elem">2</li>
<li>3</li>
<li>4</li>
<li class="elem">5</li>
<li>6</li>
<li>7</li>
<li class="elem">8</li>
<li>9</li>
</ul>
Write a selector that selects elements immediately after .elem elements.