CSS general sibling selector

Sometimes we need to define css style for general sibling elements. These may not be adjacent but should have same container parent. It can be defined by using syntax E1 ~ E2. It will match when E2 follows E1 (need not be adjacent) and have same parent. The style will apply to E2.

Example – general sibling selector

In this example:

  • If a div follows a sibling h2 (may not be adjacent), keep a left margin.
  • For all other divs there won’t be any left margin
  • Keep same left-margin for h2 also
<style type="text/css">
div {
  width:100px; background-color: lightgray; margin-bottom:10px;
}
h2, h2 ~ div {
  margin-left: 20px;
}   
</style>

<h1>h1</h1>
<div>div1</div>
<div>div2</div>
<h2>h2</h2>
<div>div3</div>
<div>div4</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