CSS adjacent sibling selector

Sometime we need to define css style for adjacent sibling elements. It can be defined by using syntax E1 + E2. It will match when E2 is adjacent to E1 and have same parent. The style will apply to E2.

Example – adjacent sibling selector

In this example:

  • In box1 vertical space above h2 is reduced when it is preceded by h1
  • In box2 vertical space above h2 is default
<style type="text/css">
div {
  width:100px; background-color: lightgray;
}
.box1 h1 + h2 {
  margin-top: -20px;
}   
</style>

<div class="box1">
  <h1>h1</h1><h2>h2</h2>
</div>
<div class="box2">
  <h1>h1</h1><h2>h2</h2>
</div>
refresh

Related

Specification

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments