CSS Previous Sibling Selector
CSS Previous Sibling Selector
In CSS, the previous sibling selector is a method of applying styles by selecting the previous sibling element of a specified element. This selector is represented by the symbol ~
, which can easily select all the sibling elements preceding the target element.
Syntax
The syntax of the previous sibling selector is as follows:
element1 ~ element2 {
/* Style rules */
}
Here, element1
is the target element, and element2
is the previous sibling element of the target element. The two are connected by ~
.
Example
Assume the following HTML structure:
<!DOCTYPE html>
<html>
<head>
<style>
p ~ span {
color: red;
}
</style>
</head>
<body>
<h2>Title</h2>
This is a paragraph of text.
<div>This is a div</div>
<span>This is a span.</span>
</body>
</html>
In the example above, the following sibling element of the <span>
element will turn red because we used the previous sibling selector, p ~ span
, to select all following sibling elements of the <span>
element.
Practical Applications
1. Navigation Menu
In navigation menus, we often use the previous sibling selector to add special styles to the active menu items.
<!DOCTYPE html>
<html>
<head>
<style>
.nav-item {
display: inline-block;
margin-right: 10px;
}
.nav-item ~ .nav-item {
color: #888;
}
.nav-item.active {
color: blue;
}
</style>
</head>
<body>
<div class="nav">
Home
About us
Service items
Contact Us
</div>
</body>
</html>
In the above example, the style of .nav-item.active
overrides the styles of .nav-item ~ .nav-item
, thereby adding special styles to the active menu item.
2. Table Styles
The previous sibling selector can also be used in tables to add separators to each column.
<!DOCTYPE html>
<html>
<head>
<style>
table { border-collapse: collapse;
}
th, td {
border: 1px solid #000;
padding: 5px;
}
th ~ td {
border-left: none;
}
</style>
</head>
<body>
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
<tr>
<td>Xiaoming</td>
<td>25</td>
<td>Male</td>
</tr>
<tr>
<td>Xiaohong</td>
<td>23</td>
<td>Female</td>
</tr>
</table>
</body>
</html>
In the above example, the th ~ td
selector is used to add a left rule to each column in the table, improving readability.
Summary
The CSS Previous Sibling Selector is a very useful selector that allows developers to quickly and easily apply styles to the previous sibling of a target element. In practical applications, we can flexibly apply the Previous Sibling Selector to improve the style and layout of a page.