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:
<h2>text</h2>
<p>
+
</p>
<p>
-
</p>
<p>
-
</p>
h2 + p {
color: red;
}
:
Example
Let's target all p tags immediately after elements with class .test and color them red:
<p class="test">
text
</p>
<p>
+
</p>
<p>
-
</p>
.test + p {
color: red;
}
:
Example
Let's target all elements with class .elem immediately after elements with class .test and color them red:
<p class="test">
text
</p>
<p class="elem">
+
</p>
<p>
-
</p>
.test + .elem {
color: red;
}
:
Practical tasks
Given code:
<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.
Given code:
<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.