Understanding the Adjacent Sibling Selector in CSS: A Practical Guide


Adjacent Sibling Selector (+)

An Adjacent Sibling Selector in CSS, denoted by the plus symbol +, is used to target and apply styles to an element that is immediately preceded by a specific element with the same parent. It allows you to select elements based on their position within the HTML structure when they share the same parent.

Syntax: The syntax for an adjacent sibling selector is as follows:

element1 + element2 {
  /* CSS styles go here */
}

Source Code :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Adjacent Sibling Selector</title>
    <style>
      div + p {
        color: red;
      }
    </style>
  </head>
  <body>
    <h2>Adjacent Sibling Selector (+)</h2>

    <p>The + selector is used to select an element that is directly after another specific element.</p>

    <div>
      <p>DIV PARA - Lorem ipsum dolor sit amet consectetur adipisicing elit. Optio repellendus, inventore architecto dolorum reiciendis et.</p>
      <section>
        <p>SECTION PARA - Lorem ipsum dolor sit amet consectetur adipisicing elit. Optio repellendus, inventore architecto dolorum reiciendis et.</p>
      </section>
    </div>
    <p>PARA - Lorem ipsum dolor sit amet consectetur adipisicing elit. Optio repellendus, inventore architecto dolorum reiciendis et.</p>

    <p>PARA - Lorem ipsum dolor sit amet consectetur adipisicing elit. Optio repellendus, inventore architecto dolorum reiciendis et.</p>
  </body>
</html>

Live Preview

The provided CSS code div + p { color: red; } is an Adjacent Sibling Selector that targets and applies styles to <p> elements that immediately follow <div> elements in the HTML structure.

div + p: This is an adjacent sibling selector composed of two selectors separated by a plus symbol (+)

{ color: red; }: This is a CSS declaration block enclosed within curly braces {}.

The primary purpose of this CSS rule is to change the text color of <p> elements that directly follow <div> elements to "red."

In summary, the CSS code div + p { color: red; } is used to selectively change the text color of <p> elements that directly follow <div> elements to "red" while leaving other <p> elements unaffected.


CSS Tutorial


Properties Reference


Cascading Style Sheet


Flexbox Tutorial


CSS Grid Tutorial


Transitions Properties


CSS Properties with Examples


CSS Selectors


CSS Pseudo Elements


CSS Attribute Selectors


Input Pseudo Classes


CSS Examples


CSS Animation Projects