CSS Basic
CSS element1 ~ element2 Selector
Photo Credit to CodeToFun
🙋 Introduction
The general sibling combinator element1 ~ element2
in CSS allows you to select an element that is a sibling of another specified element.
This selector is particularly useful for applying styles to elements that share the same parent and come after the specified element in the document order.
💡 Syntax
The signature of the element1 ~ element2
Selector is as follows:
element1 ~ element2 {
/* CSS properties */
}
This syntax targets element2
when it is preceded by element1
and both elements share the same parent.
📝 Example
Here is an example of how to use the element1 ~ element2
selector in CSS:
☠️ HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS element1 ~ element2 Selector Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h2>Heading 1</h2>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<h2>Heading 2</h2>
<p>This is another paragraph.</p>
</div>
</body>
</html>
🎨 CSS
h2 {
color: blue;
}
h2 ~ p {
color: green;
font-style: italic;
}
In this example:
- All
<h2>
elements are styled with a blue color. - Any
<p>
element that follows an<h2>
element within the same parent (in this case,.container
) will be styled with a green color and italic font style.
💬 Usage Tips
- Use the
~
selector to style multiple elements that follow a specific element. For example, you can style all paragraphs following a heading without needing to target each paragraph individually. - This selector is particularly useful in creating dynamic layouts where the styling of elements can change based on their position relative to other elements.
⚠️ Common Pitfalls
- The
~
combinator only applies to siblings that come after the specified element. If the specified element appears later in the document, the styles will not apply. - Ensure that the elements are siblings; if they are not direct siblings (i.e., they do not share the same parent), the selector will not work.
🎉 Conclusion
The element1 ~ element2
selector is a versatile tool for targeting sibling elements in your CSS.
By understanding how to use this combinator, you can create more flexible and dynamic styles for your web projects, allowing for enhanced layouts and design options.
👨💻 Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (CSS element1 ~ element2 Selector), please comment here. I will help you immediately.