Menu
Coddy logo textTech

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 icon

Challenge

Easy
  • Create a web page with a p element and a span element.
  • Use an adjacent sibling selector to style the span element that is immediately adjacent to the p element 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