Adjacent Sibling Selectors in CSS


The CSS adjacent sibling selector is used to select the adjacent sibling of an element. It is used to select only those elements which immediately follow the first selector. The + sign is used as a separator. For example, the direct next element is selected here with the adjacent sibling selector concept −

Syntax

The syntax for CSS adjacent sibling selector is as follows −

element + element {
   /*declarations*/
}

Adjacent Sibling Selector Example

Example

The following example illustrate CSS adjacent sibling selector −

<!DOCTYPE html>
<html>
<head>
   <style>
      div {
         margin: 8px;
         height: 50px;
         width: 60px;
         display: flex;
         float: left;
         border-radius: 5%;
         border: 2px solid brown;
         box-shadow: inset 0 2px 12px olivedrab;
      }
      div + div {
         border-radius: 50%;
         background-color: orange;
      }
   </style>
</head>
<body>
   <div></div>
   <hr>
   <div></div>
   <div></div>
</body>
</html>

Next Span Element is Selected by the + Selector

Example

In this example, the direct next <span> element is selected by the + selector −

<!DOCTYPE html>
<html>
<head>
   <style>
      p {
         font-size: 1.5em;
      }
      span {
         background-color: lavender;
      }
      span + span {
         background-color: darkseagreen;
      }
   </style>
</head>
<body>
   <p>
      <span>Demo text</span>   <span>goes here</span>
   </p>
</body>
</html>

Direct Next Element is Selected by the + Selector

Example

In this example, the direct next element is selected by the + selector −

<!DOCTYPE html>
<html>
<head>
   <style>
      div + p {
         color: white;
         background-color: red;
         border: 2px solid green;
      }
   </style>
</head>
<body>
   <h1>Demo Heading</h1>
   <div>
      <p>Demo text 1</p>
      <p>Demo text 2</p>
   </div>
   <p>Demo text 3</p>
   <div>
      <p>Demo text 4</p>
      <p>Demo text 5</p>
      <p>Demo text 6</p>
      <p>Demo text 7</p>
      <p>Demo text 8</p>
   </div>
   <p>Demo text 9</p>
</body>
</html>

Next p Element is Selected Immediately After a p

Example

In this example, the <p> is selected immediately after a <p> −

<!DOCTYPE html>
<html>
<head>
   <style>
      p + p {
         color: white;
         background-color: red;
         border: 2px solid green;
      }
   </style>
</head>
<body>
   <h1>Demo Heading</h1>
   <div>
      <p>Demo text 1</p>
      <p>Demo text 2</p>
   </div>
   <div>
      <p>Demo text 3</p>
      <p>Demo text 4</p>
      <p>Demo text 5</p>
      <p>Demo text 6</p>
      <p>Demo text 7</p>
   </div>
   <p>Demo text 8</p>
</body>
</html>

Updated on: 27-Oct-2023

962 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements