CSS previous sibling element
CSS Previous Sibling Element
In CSS, you can use the pseudo-classes :first-child
and :last-child
to select the first and last child of an element. However, sometimes you may need to select the previous sibling of an element. This can be achieved using the :nth-last-child()
pseudo-class.
What is the Previous Sibling?
The previous sibling is the sibling element that immediately precedes the target element in the DOM. For example, in the following HTML structure, the previous sibling of <div class="target"></div>
is <p>Paragraph</p>
.
<p>Paragraph</p>
<div class="target"></div>
How to Select the Previous Sibling
To select the previous sibling of an element, use the :nth-last-child()
pseudo-class in conjunction with the +
operator. :nth-last-child()
accepts an argument, n, to select the nth-to-last child, while the +
operator selects the immediately preceding element.
.target {
color: red;
}
.target + p {
/* Selects the p element preceding the target element */
font-weight: bold;
}
In the above example, .target + p
selects the <p>
element preceding .target
and makes it bold.
Example Code
Let’s use a simple example to demonstrate how to select the previous sibling of an element. Suppose we have the following HTML structure:
<div>
<p>Paragraph 1</p>
<span>Span 1</span>
</div>
<div>
<p>Paragraph 2</p>
<span class="target">Span 2</span>
</div>
<div>
<p>Paragraph 3</p>
<span>Span 3</span>
</div>
Now, we want to select the previous sibling of each <span>
element, that is, the adjacent <p>
element, and set its text color to red.
span + p {
color: red;
}
In the code above, we use the span + p
selector to select the p
element preceding each span
element and set its text color to red.
Running Results
Based on the above sample code, we can get the following running results:
<div>
<p style="color: red;">Paragraph 1</p>
<span>Span 1</span>
</div>
<div>
<p style="color: red;">Paragraph 2</p>
<span class="target">Span 2</span>
</div>
<div>
<p style="color: red;">Paragraph 3</p>
<span>Span 3</span>
</div>
As you can see, the text color of each preceding <span>
element has been successfully set to red.
Summary
In CSS, selecting the previous sibling of an element can be achieved by using the :nth-last-child()
pseudo-class in conjunction with the +
operator. This method can easily help us achieve various styling effects and enhance the visual experience of the web page.