General sibling selector
Lesson 10 of 15 in Coddy's CSS Selectors course.
In this lesson, we'll explore the concept of general sibling selectors, a powerful way to target and style elements that share the same parent and come after a specific element.
General sibling selectors allow you to target elements that share the same parent and appear after a certain element. This selector is denoted by using the tilde (~) symbol.
Syntax:
element ~ target-element {
/* Styles applied to target-element */
}Example:
HTML:
<div class="box"></div>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<div class="highlight"></div>
<p>Paragraph 4</p>CSS:
.box ~ p {
color: gray;
}In the provided example, all <p> elements that appear after the <div class="box"> element will have their text color set to gray. The general sibling selector (~) targets and styles the subsequent <p> elements after the specified <div>.
Challenge
EasyGiven the HTML structure, apply a unique background color to all <h3> elements that come after the <h2> element.
Try it yourself
<html>
<head>
<title>General Sibling Selector Exercise</title>
<style>
</style>
</head>
<body>
<div class="content">
<h2>Introduction</h2>
<p>Content goes here...</p>
<h3>Subsection 1</h3>
<p>More content...</p>
<h3>Subsection 2</h3>
<p>Even more content...</p>
</div>
</body>
</html>
All lessons in CSS Selectors
3Combinator Selectors
Child selectorDescendant selectorAdjacent sibling selectorGeneral sibling selector