CSS tilde selector
CSS Tilde Selector
In CSS, the tilde selector ( selector) is a selector used to select sibling elements of a specified element within the same parent element. By putting a tilde (~) between element names, you can select sibling elements that appear after the specified element.
Syntax
The syntax of the tilde selector is as follows:
element1 ~ element2 {
/* styles */
}
Here, element1 is the reference element to be selected, and element2 is the sibling element to be selected. The tilde (~) connects the two elements, selecting all sibling elements of element2 that appear after element1.
Example
Let’s use an example to demonstrate the use of the tilde selector. Suppose we have the following HTML structure:
<div class="container">
<h2>Heading 1</h2>
<p>Paragraph 1</p>
<h2>Heading 2</h2>
<p>Paragraph 2</p>
<h2>Heading 3</h2>
<p>Paragraph 3</p>
</div>
Now we want to select each <p>
tag that appears after the corresponding <h2>
tag. We can achieve this effect using the tilde selector:
h2 ~ p {
font-weight: bold;
}
In the example above, we use the h2 ~ p
selector to select each element that appears after the corresponding <p>
tag and make its font bold.
Notes
When using the tilde selector, please note the following:
- The tilde selector can only select sibling elements that appear after the specified element, not before.
- If there are no sibling elements after the specified element that meet the criteria, the selector will not work.
- The tilde selector can select preceding and following sibling elements, but not preceding sibling elements.
In summary, the tilde selector is a simple yet powerful CSS selector that conveniently selects sibling elements that appear after a specified element within the same parent element, providing more flexibility and selectivity for page layout and style design.