Selecting immediate Sibling Elements

Description

The immediate sibling selector selects elements that immediately follow other elements.

  • Selector: firstSelector + secondSelector
  • Matches: Selects elements that match the secondSelector and immediately follow an element that matches the firstSelector
  • CSS Version: 2

Example

The following code shows how you can select immediate sibling elements.


<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
p + a {<!--from ww  w . j  av a2s .  c o m-->
  border: thin black solid;
  padding: 4px;
}
</style>
</head>
<body>
  <a href="http://java2s.com">Visit the website</a>
  <p>
    This is <span lang="en-uk" class="class2">a</span> test.
  </p>
  <a href="http://w3c.org">Visit the W3C website</a>
  <a href="http://google.com">Visit Google</a>
</body>
</html>

Click to view the demo

The selector will match a elements that immediately follow a p element.

Example 2

You can add more than one level.


<html>
<head>
<style type='text/css'>
body {<!--from w  w  w  .  j  a v  a 2 s .  c  om-->
  font: 12px sans-serif;
}

p {
  padding: 5px;
}

h1+p {
  background: lightyellow;
  color: darkkhaki;
  border: 1px solid darkkhaki;
}

h1+p+p {
  background: yellowgreen;
  color: green;
  border: 1px solid green;
}
</style>
</head>
<body>
  <h1>Next Sibling Selectors</h1>
  <p>The next sibling selector allows you to select an element based
    on its sibling.</p>
  <p>This paragraph has a yellowgreen background and green text.</p>
  <p>This paragraph has no colored background, border, or text.</p>
</body>
</html>

Click to view the demo





















Home »
  HTML CSS »
    CSS »




CSS Introduction
CSS Background
CSS Border
CSS Box Layout
CSS Text
CSS Font
CSS Form
CSS List
CSS Selectors
CSS Others
CSS Table