Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

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" "https://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:

simple-example-CSS-adjacent-sibling-selector

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" "https://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:

advanced-example-CSS-adjacent-sibling-selector

View this advanced example of CSS adjacent sibling selector in a separate browser window.

Previous: CSS child selectors
Next: CSS attribute selectors