CSS selects the previous sibling node

CSS Select Previous Sibling Node

CSS Select Previous Sibling Node

In CSS, we often need to select the previous sibling of an element. This requires the use of specialized CSS selectors. In this article, we’ll discuss how to select the previous sibling using CSS.

What is the Previous Sibling?

In HTML documents, siblings are elements that share the same parent element. The previous sibling is the sibling that comes before the current element under the same parent element. For example, in the following HTML code:


<div>
<p>First Sibling</p>
<p>Second Sibling</p>
<p id="target">Target Element</p>
<p>Fourth Sibling</p>
</div>

In this example, the p element “Second Sibling” is the previous sibling of the element “Target Element.”

Selecting the Previous Sibling with CSS

To select the previous sibling of an element, we can use the sibling and adjacent sibling selectors in CSS.

Sibling Selector (~)

The sibling selector (tilde symbol ~) selects all preceding sibling elements that match the specified selector. We can achieve this by linking the target element and its previous sibling with a sibling selector. For example:

#target ~ p {
color: red; 
} 

The above code will select all p elements following the target element and set their text color to red. This effectively selects the previous sibling.

Adjacent Sibling Selector (+)

The adjacent sibling selector (the plus sign +) selects the sibling element immediately following the specified element. We can achieve this by linking the target element with its previous sibling using the adjacent sibling selector. For example:

#target + p {
font-weight: bold; 
} 

The above code will select the p element immediately following the target element and set its text to bold. This effectively selects the previous sibling.

Practical Application

Below, we’ll use a specific example to demonstrate how to use CSS to select the previous sibling node. Suppose we have the following HTML code:

<ul>
<li>Apple</li>
<li>Banana</li>
<li class="selected">Orange</li>
<li>Watermelon</li>
</ul>

We want to add special styling to the selected fruit and also to the previous sibling of the selected fruit. We can achieve this with the following CSS code:

.selected {
color: red;
}

.selected + li {
font-weight: bold;
}

This will set the text of the selected fruit to red and the text of the previous sibling of the selected fruit to bold.

Conclusion

In this article, we discussed in detail how to select the previous sibling of an element using CSS. By using the sibling and adjacent sibling selectors, we can easily select the previous sibling of an element and add styles or perform other operations on it.

Leave a Reply

Your email address will not be published. Required fields are marked *