Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to style every element that have adjacent item right before it?
The CSS adjacent sibling selector allows you to style elements that come immediately after another element. This selector uses the plus (+) symbol to target elements that share the same parent and are positioned directly next to each other in the HTML structure.
Syntax
former_element + target_element {
/* CSS properties */
}
The adjacent sibling selector will only select the first element that immediately follows the specified element. Both elements must share the same parent element.
Example: Basic Adjacent Sibling Selection
The following example demonstrates how to style paragraphs that come directly after an image
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: #2196F3;
text-align: center;
}
img + p {
color: #FF9800;
font-weight: bold;
font-size: 18px;
}
img + p + p {
color: #4CAF50;
font-style: italic;
}
</style>
</head>
<body>
<h1>Adjacent Sibling Selector Example</h1>
<img src="/css/images/css-mini-logo.jpg" alt="CSS Logo" width="100">
<p>This paragraph comes immediately after the image.</p>
<p>This is the second paragraph after the image.</p>
<p>This is the third paragraph after the image.</p>
</body>
</html>
The first paragraph after the image appears in orange and bold. The second paragraph appears in green and italic. The third paragraph remains unstyled with default formatting.
Example: Styling Form Elements
Here's a practical example using the adjacent sibling selector for form styling
<!DOCTYPE html>
<html>
<head>
<style>
label {
display: block;
margin: 10px 0 5px 0;
font-weight: bold;
}
input[type="text"] + label {
color: #E91E63;
margin-top: 20px;
}
input[type="email"] + button {
background-color: #4CAF50;
color: white;
padding: 8px 16px;
border: none;
margin-left: 10px;
}
</style>
</head>
<body>
<form>
<label>First Name:</label>
<input type="text" name="fname">
<label>Email Address:</label>
<input type="email" name="email">
<button type="submit">Submit</button>
</form>
</body>
</html>
A form with styled labels appears. The "Email Address" label is colored pink due to the adjacent sibling selector, and the submit button has a green background when placed after the email input.
Key Points
- The
+selector targets only the immediately adjacent sibling element - Both elements must share the same parent element
- Only the first matching adjacent element is selected
- Use
~for general sibling selection (not just adjacent)
Conclusion
The adjacent sibling selector (+) is a powerful CSS combinator for styling elements based on their position relative to other elements. It's particularly useful for form styling, content formatting, and creating visual relationships between adjacent elements that share the same parent.
