Adjacent sibling selector
Lesson 9 of 15 in Coddy's CSS Selectors course.
Let's dive into adjacent sibling selectors. These selectors target elements that share the same parent and come immediately after the selected element.An adjacent sibling selector is a CSS selector that selects all elements that are siblings of a specified element, and are immediately adjacent to it. The adjacent sibling selector is denoted by a plus sign (+) between two selectors.
Syntax
former_element + target_element {
/* style properties */
}Suppose we have this HTML structure:
<div class="container">
<p>First paragraph</p>
<span>Adjacent span</span>
<p>Second paragraph</p>
</div>To style the <span> immediately following a paragraph, you would use the adjacent sibling selector:
p + span {
font-weight: bold;
}In this instance, the "Adjacent span" will have bold font weight.
Challenge
Easy- Create a web page with a
pelement and aspanelement. - Use an adjacent sibling selector to style the
spanelement that is immediately adjacent to thepelement to have a red border.
Try it yourself
<html>
<head>
<title>Adjacent Sibling Selector Exercise</title>
<style>
/* CSS Code goes here */
</style>
</head>
<body>
</body>
</html>
All lessons in CSS Selectors
3Combinator Selectors
Child selectorDescendant selectorAdjacent sibling selectorGeneral sibling selector