In CSS, combinators are very important tools that allow us to select more complex and smarter elements from among existing HTML elements. One of these combinators is "general sibling" (~
), which allows us to select a specific element sibling that follows that element. In this article, we intend to show you how you can use this combinator and in the examples we provide, you will be able to apply it in real-world projects.
Before anything, we must understand that combinators are operations that enable us to define relationships between DOM elements. Regarding the general sibling combinator, this combinator allows us to target elements that follow a specific element and are of the same type. For example, suppose you want to select all siblings of a specific element that follow it in the document, let’s learn.
The general sibling combinator is commonly used in responsive designs and interactions. For instance, you might want an element that is activated by JavaScript to affect its siblings that come after it, applying your styles to them. This functionality can help creators with innovative designs.
To understand better, let’s look at a simple example that shows how to use the general sibling combinator for more advanced structures.
<style>
div.example > p {
background-color: lightblue;
padding: 10px;
}
div.example > p ~ span {
color: red;
font-weight: bold;
}
</style>
<div class="example">
<p>This paragraph is the first.</p>
<span>This is an important text.</span>
<p>This paragraph is the second.</p>
<span>This is another important text.</span>
</div>
In this code:
<style>
begins the CSS section where we define the styles. Using div.example > p
, we select all direct paragraphs within the "example" that have a light blue background and padding applied.
div.example > p ~ span
targets all <span>
elements that follow the direct paragraph inside "example" with red color and bold font weight applied.</style>
ends the CSS section.This example demonstrates how to use the general sibling combinator to select subsequent elements for styling purposes.