CSS sibling element selector previous
CSS Sibling Selector Previous
In CSS, the sibling selector is used to select sibling elements of a specified element. Sibling selectors can be divided into two types: previous sibling selector and next sibling selector.
In this article, we’ll focus on the usage and examples of the previous sibling selector in CSS to help readers better understand and master its use.
Previous Sibling Selector
The previous sibling combinator, denoted by the symbol ~
in CSS, selects all sibling elements preceding the specified element. This means that the element specified in the selector must be under the same parent element and before the specified element to be selected.
The syntax is as follows:
selector1 ~ selector2 {
/* styles */
}
Where selector1
represents the specified element, and selector2
represents the sibling element to be selected.
Example
To better understand the use of the previous sibling selector, let’s use a simple example to demonstrate its effect.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Previous Sibling Selector Example</title>
<style>
div {
border: 1px solid black;
padding: 10px;
margin: 10px;
}
.first {
background-color: lightblue;
}
.second {
background-color: lightcoral;
}
.third {
background-color: lightgreen;
}
.second ~ .third {
color: white;
}
</style>
</head>
<body>
<div class="first">First</div>
<div class="second">Second</div>
<div class="third">Third</div>
</body>
</html>
In the above example, we define three <div>
elements with the classes .first
, .second
, and .third
, respectively. We set different background colors to distinguish these elements, and use the previous sibling selector, .second ~ .third
, to select the .third
element following the .second
element and set its text color to white.
Running Results
According to the above code, we can see that three <div>
elements with different background colors are displayed on the page. When viewing the page in a browser, we can see that the text color of the .third
element has changed to white. This is because the previous sibling selector has selected the .third
element following the .second
element and set its text color to white.
Through this simple example, we can clearly see the effect of the sibling selector in CSS, which will help us better understand and apply this selector.
Summary
This article detailed the usage and examples of the previous sibling selector in CSS, and demonstrated its effectiveness through code demonstrations. By studying this article, readers can better understand and master the use of the previous sibling selector, thereby flexibly applying this selector to implement page styling in actual development.