CSS selector for the previous sibling element

CSS Selector Previous Sibling Element

CSS Selector Previous Sibling Element

In CSS, a selector is a method used to determine which elements will be styled. When we want to select the preceding sibling element of an element, we can use the CSS adjacent sibling selector.

What is the adjacent sibling selector?

The adjacent sibling selector is used to select the element that immediately follows another element. In CSS, the symbol for the adjacent sibling selector is “+”. Its format is:


element1 + element2 {
/* styles */
}

Where element1 is the preceding sibling element, and element2 is the following sibling element. The styles will be applied to element2 only if element2 is placed immediately after element1.

How to Use the Adjacent Sibling Selector?

Let’s use the adjacent sibling selector with a simple example. Suppose we have an HTML document containing a set of list items. We want to make the preceding sibling element (if any) of each list item red.

<!DOCTYPE html> 
<html> 
<head> 
<style> 
.list-item + .list-item { 
color: red; }
</style>

</head>

<body>

<ul>

<li class="list-item">Item 1</li>

<li class="list-item">Item 2</li>

<li class="list-item">Item 3</li>

</ul>

</body>

</html>

In the example above, we use the .list-item + .list-item selector to select the .list-item element that immediately follows the previous .list-item element. We set a red text color for such elements. Therefore, Item 2 and Item 3 will turn red.

Application Scenarios of the CSS Previous Sibling Selector

The adjacent sibling selector has many practical uses in development. Here are some common use cases:

  1. Navigation bar effects: In a website’s navigation bar, when you hover over an option, the previous option’s style changes.
  2. Table design: To create a different spacing style between rows in a table, use the adjacent sibling selector.

  3. Step Indicator: In a series of step indicators, mark the previous step as completed.

  4. Comment Area Design: The separator lines between each comment in the comment area have different styles.

Summary

By using CSS’s adjacent sibling selector, we can easily select and style the previous sibling of an element. Adjacent sibling selectors are very useful when designing web pages, helping us achieve more complex and diverse styling effects.

Leave a Reply

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