Mastering the General Sibling Selector in CSS: A Comprehensive Guide


General Sibling Selector (~)

A General Sibling Selector in CSS, denoted by the tilde symbol ~, is used to target and apply styles to elements that are siblings of a specific element with the same parent. It allows you to select elements based on their shared parent and position in the HTML structure, regardless of whether they are immediate siblings or not.

Syntax: The syntax for a general 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>General Sibling Selector</title>
    <style>
      div ~ p {
        color: red;
      }
    </style>
  </head>
  <body>
    <h2>General Sibling Selector (~)</h2>

    <p>The general sibling selector (~) selects all elements that are next siblings of a specified 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>
    <h2>Heading</h2>
    <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>

    <section>
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum odit sunt modi enim. Quod, porro!</p>
    </section>
  </body>
</html>

Live Preview

The provided CSS code div ~ p { color: red; } is a General Sibling Selector that targets and applies styles to <p> elements that are siblings of <div> elements within the same parent in the HTML structure.

div ~ p: This is a general sibling selector consisting of two selectors separated by a tilde symbol (~)

In summary, the general sibling selector is a useful tool for targeting and applying styles to elements that share the same parent and are positioned before or after a specific reference element, regardless of whether they are immediate siblings or not. It allows for more flexible styling based on sibling relationships in the HTML structure.


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