Loading
CSS Combinators
CSS combinators are used to select and style HTML elements based on their relationships with other elements in the document hierarchy. They are especially useful for targeting specific structures in your HTML layout.



Types of CSS Combinators

CombinatorSymbolDescription
Descendant(space)Selects all elements that are descendants of a specified element
Child>Selects direct children only
Adjacent Sibling+Selects a n element that comes immediately after another 
General Sibling~Selects all siblings that follow the specified element



1. General Sibling Combinator ( ~ )

Selects all siblings after a specified element that share the same parent.


Syntax:

element1 ~ element2 {
  /* styles */
}


Example:

HTML

<h1>General Sibling Example</h1>
<p>This is affected</p>
<div>
  <p>This paragraph under div is not affected</p>
</div>
<p>This is affected</p>
<p>This is also affected</p>


CSS

h1 ~ p {
  color: blue;
  font-weight: bold;
}

Output:

Uploaded Image




2. Adjacent Sibling Combinator ( + )

Selects an element that is immediately after a specified sibling.


Syntax:

element1 + element2 {
  /* styles */
}


Example:

HTML

<p>This is the first paragraph</p>
  <p>This is the second paragraph - affected</p>
  <div>This is a div</div>
  <p>This paragraph is not affected</p>
  <p>This paragraph is affected (adjacent to previous paragraph)</p>


CSS

p + p {
  color: blue;
  font-size: 20px;
}

Output:

Uploaded Image




3. Child Combinator ( > )

Selects direct children of an element.


Syntax:

parent > child {
  /* styles */
}


Example:

HTML

<div>
    <p>This is a child - affected</p>
    <div>
      <p>This is a nested paragraph - not affected</p>
    </div>
  </div>


CSS

div > p {
  color: blue;
  font-size: 20px;
}

Output:

Uploaded Image




4. Descendant Combinator ( Whitespace )

Selects all nested elements, whether direct children or deeply nested.


Syntax:

ancestor descendant {
  /* styles */
}


Example:

HTML

<div>
    <section>
      <p>This will be selected by div p</p>
    </section>
  </div>


CSS

div p {
  color: green;
}

Output:

Uploaded Image