CSS Sibling Selectors – Previous
CSS Sibling Selectors – Previous
In CSS, the sibling selector is a very useful selector that allows you to select specific sibling elements within the same parent element. Sibling selectors allow us to control the relationships between elements, enabling more flexible layout and styling. This article focuses on a special case of the CSS sibling selector: the previous sibling selector.
What is the previous sibling selector?
The previous sibling selector is used to select the previous sibling of a specified element. We use the symbol ~
to represent the previous sibling selector. Using the previous sibling selector, you can easily select and apply styles to the previous sibling of an element.
How to Use
We can use the previous sibling selector with the following syntax:
selector1 ~ selector2 {
/* Style rule */
}
Where selector1 is the element to be selected, selector2 is the previous sibling element to which the style is applied. This way, we can apply style settings to both a specific element and its previous sibling.
Example Demonstration
Let’s use a simple example to demonstrate the use of the sibling selector:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Previous Sibling Selector Example</title>
<style>
.item {
color: red;
}
.item ~ .item {
color: blue;
}
</style>
</head>
<body>
<div class="container">
<div class="item">First element</div>
<div class="item">Second element</div>
<div class="item">Third element</div>
</div>
</body>
</html>
In the example above, we have three elements with the same class name. We use the previous sibling selector, .item ~ .item
, to select all elements except the first one and set their text color to blue. This way, the first element remains red, while subsequent elements become blue.
Advanced Usage
The previous sibling selector can be combined with other selectors for even more flexible styling control. Here’s an advanced usage example:
h2 ~ p:first-of-type {
color: green;
}
h2 ~ p:last-of-type {
color: purple;
}
In this example, by combining the previous sibling selector with the :first-of-type
and :last-of-type
pseudo-class selectors, we apply different color styles to the first and last <p>
elements after the <h2>
element, respectively. This makes the page style more diverse and interesting.
Summary
Through this article, we have a detailed understanding of the usage and practical applications of the sibling selector in CSS. The previous sibling selector is a very useful selector in CSS. It helps us precisely control the relationships between page elements, achieving more flexible and diverse page layouts and styling effects.