General Sibling Selector
In CSS, the general sibling selector is used to select an element that is preceded by another element. The general sibling selector is represented by the ~
character between two selectors.
Syntaxβ
The syntax for the general sibling selector is as follows:
selector1 ~ selector2 {
/* CSS properties */
}
selector1
: The first sibling element.selector2
: The second sibling element.CSS properties
: The CSS properties to be applied to the second sibling element.~
: The~
character represents the general sibling selector.- The
~
character is used to select all sibling elements that are preceded by the first sibling element.
Exampleβ
In the following example, the general sibling selector is used to select all <p>
elements that are preceded by an <h2>
element:
h2 ~ p {
font-weight: bold;
}
In the HTML code below, the CSS rule will apply the font-weight: bold
property to the text inside the <p>
element because it is preceded by an <h2>
element.
- The general sibling selector is represented by the
~
character between two selectors. - The general sibling selector selects an element that is preceded by another element.
- The general sibling selector is less specific than the adjacent sibling selector (
+
) and more specific than the descendant combinator ( - The general sibling selector is also known as the tilde combinator.
- The general sibling selector can be used to target multiple sibling elements that are preceded by the first sibling element.
- The general sibling selector is useful for styling elements that are not directly related but share the same parent.
Example: Using General Sibling Selectorβ
In the following example, the general sibling selector is used to select all <p>
elements that are preceded by an <h2>
element:
- HTML
- CSS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>General Sibling Selector Example</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<h2>Heading</h2>
<p>This text will be bold.</p>
<p>This text will also be bold.</p>
<h2>Another Heading</h2>
<p>This text will be bold too.</p>
</body>
</html>
h2 ~ p {
font-weight: bold;
}
Now, you can see the output of the above code in the Browser Window like this:
Heading
This text will be bold.
This text will also be bold.
Another Heading
This text will be bold too.
In the above example, the CSS rule will apply the font-weight: bold
property to the text inside the <p>
elements that are preceded by an <h2>
element.
Summaryβ
The general sibling selector (~
) is used to select an element that is preceded by another element. It is less specific than the adjacent sibling selector (+
) and more specific than the descendant combinator (
). The general sibling selector is useful for styling elements that are not directly related but share the same parent.