CSS selects the previous sibling element of the current element
CSS Select the Previous Sibling of the Current Element
When writing CSS styles, you often need to select the styles of an element’s previous sibling. This is very useful in layout and design. In this article, we’ll discuss in detail how to use CSS selectors to select the previous sibling of the current element, and provide some sample code and results.
Using the CSS Selector “~” to Select the Previous Sibling Element
The tilde “~” in the CSS selector selects the previous sibling of the current element. This selector specifies that the selected element must be a sibling of the current element, but not necessarily a directly adjacent one.
Here is a simple example code that demonstrates how to use the CSS selector “~” to select the previous sibling element:
<!DOCTYPE html>
<html Tutorial">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>CSS Select Previous Sibling Element</title>
<style>
p ~ p {
color: red;
}
</style>
</head>
<body>
First Paragraph
Second Paragraph
Third Paragraph
</body>
</html>
In this example, we use the CSS selector “p ~ p” to select all paragraph elements. This means that the second and third paragraphs will have red text color applied to them.
Advanced Example: Selecting the Previous Sibling of a Specific Type
In addition to selecting all previous sibling elements, we can also select the previous sibling element based on a specific element type. Here’s an advanced example code:
<!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>CSS Select Previous Sibling Element</title>
<style>
div ~ p {
color: blue;
}
</style>
</head>
<body>
<div>This is a div</div>
First Paragraph
Second Paragraph
Third Paragraph
</body>
</html>
In this example, we use the CSS selector “div ~ “p” selects all paragraph elements, but applies the blue text color only if there’s a preceding div element.
Summary
By using the CSS selector “~”, we can select the previous sibling of the current element, and we can also select specific types of sibling elements if needed. This is a very useful technique in page layout and design, giving us greater control over the styling of elements.