CSS adjacent sibling selectors
Adjacent sibling selectors
CSS adjacent sibling selectors come as a pair of selectors and select the second one, if it immediately follows the first one in order of appearance in an HTML page.
If, x, y and z are three HTML elements and y and z resides next to each other within x, then y and z are called as adjacent sibling selectors.
While writing adjacent sibling selectors, selectors must be separated with "+" combinator.
syntax:
Selector1 + Selector2 { CSS-Property: value; ........................ }
Simple Example of CSS adjacent sibling selectors
CSS code:
h1 + h2 {
color: red; /* sets color to red */
}
HTML code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Simple Example of CSS adjacent sibling selectors</title>
<link rel='stylesheet' href='Simple-Example-of-CSS-adjacent-sibling-selector.css' type='text/css'>
</head>
<body>
<h1>w3resource CSS examples</h1>
<h2>w3resource CSS CSS adjacent selectors examples</h2>
</div>
</body>
</html>
Result:
View this simple example of CSS adjacent sibling selector in a separate browser window.
Advanced Example of CSS adjacent sibling selectors
CSS code:
.main {
background-color: aliceblue; /* sets background color to aliceblue */
}
p.main + h4 {
color: red; /* sets color to red */
}
HTML code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Advanced Example of CSS adjacent sibling selectors</title>
<link rel='stylesheet' href='Advanced-Example-of-CSS-adjacent-sibling-selector.css' type='text/css'>
</head>
<body>
<div>
<p class="main">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a urna elit.</p>
<h4>w3resource CSS examples.</h4>
</div>
</body>
</html>
Result:
View this advanced example of CSS adjacent sibling selector in a separate browser window.
Previous: CSS child selectors
Next:
CSS attribute selectors
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/css/selectors/CSS-adjacent-sibling-selectors.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics