Mahesh Mahesh - 5 months ago 7
CSS Question

What is difference between “+” and “~” selector in CSS?

I have used these selector. However, not able to get the difference them.

It seems like they both work same. Their must be some difference which I am not able to get.

Answer

+ will only select the first element that is immediately preceded by the former selector.

~ selector all the sibling preceded by the former selector.

.plusSelector + div {
  background: red
}
.tiltSelector ~ div {
  background: red
}
<h3>+ Selector</h3>
<div class="example1">
  <div class="plusSelector">test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
</div>

<h3>~ Selector</h3>
<div class="example1">
  <div class="tiltSelector">test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
</div>