CSS3 Adjacent Selector

ยท

1 min read

In CSS3 we have a lot of selectors which empower the dev's productivity and help in the optimization of DOM, and usage of classes.

One such selector is:

Adjacent Selectos ( + )

The adjacent selector in CSS is a selector that selects an element that is immediately adjacent (i.e., comes right after) to another element. The adjacent selector is represented by the plus sign (+) and is used to select the first element that immediately follows the specified element. Eg: here all p tags after H1 would get the style implemented but not the p which is coming after H2

<div>
 <h1>About us</h1>
 <p>CSS team is proud to present you...</p>
 <h1>Profile</h1>
 <p>CSS team is proud to present you...</p>
 <h1>Team</h1>
 <h2>Subheding...</h2>
 <p>CSS team is proud to present you...</p>
</div>
div h1 + p {
 color: red;
  margin-top: 10px;
}

Use cases:

  1. Whenever there is text after an image you want the margin between them.

  2. Whenever there is a paragraph after an h2 you want a specific style but if there is an h3 between them you want a different style.

Happy Learning!!