CSS Next Sibling Combinator
The CSS next sibling combinator (+
) is used to style an element that is immediately preceded by a specified element. This combinator only targets the first sibling that follows the specified element.
The syntax for the next sibling combinator is:
</>
Copy
selector1 + selector2 {
property: value;
}
Where:
Parameter | Description |
---|---|
selector1 | The preceding element. |
selector2 | The element immediately following selector1 . |
property | A CSS property (e.g., color , margin , etc.). |
value | The value assigned to the CSS property. |
Examples
Styling the First Paragraph After a Heading using Next Sibling Selector
In this example, we set the text color of the first <p>
element that immediately follows an <h1>
to blue.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
h1 + p {
color: blue;
}
</style>
</head>
<body>
<h1>Heading 1</h1>
<p>This paragraph is styled.</p>
<p>This paragraph is not styled.</p>
</body>
</html>
Styling List Items Following a Specific List Item using Next Sibling Selector
Here, we style the first <li>
that immediately follows a specific <li>
with the class highlight
, setting its font weight to bold.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
li.highlight + li {
font-weight: bold;
}
</style>
</head>
<body>
<ul>
<li class="highlight">Highlighted Item</li>
<li>This item is styled.</li>
<li>This item is not styled.</li>
</ul>
</body>
</html>
Styling Input Fields Following a Label using Next Sibling Selector
In this example, we style input fields (<input>
) that immediately follow a <label>
, setting their border color to green.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
label + input {
border: 2px solid green;
}
</style>
</head>
<body>
<label>Name:</label>
<input type="text" name="name">
<br>
<input type="text" name="unrelated">
</body>
</html>