CSS Selector - CSS immediately after Selector element+element








The element1+element2 selector adds style for element2 placed immediately after but not inside the first specified element1.

element1 + element2 is also called Adjacent Sibling Selector

This selector selects an element that is the following adjacent sibling of another element. Any text between the two elements is ignored; only elements and their positions in the document tree are considered.

Examples:

table + p  {margin-top:  2em;}
h1  + *  {margin-top: 0;}

Summary

CSS Version
2




CSS Syntax

element+element { 
   style properties 
}

Browser compatibility

element+element Yes 7.0 Yes Yes Yes

Example

An example showing how to use element+element CSS selector.

<!DOCTYPE html>
<html>
<head>
<style>
div+p{<!--from  w  w  w  .  j  av  a  2 s  .c  o m-->
   background-color:red;
}
</style>
</head>
<body>

    <div>
        <p>inside div.</p>
    </div>

     <p>after div.</p>
     <p>not immediately after div.</p>

</body>
</html>

Click to view the demo





Example 2

You can add more than one level.

<html>
<head>
<style type='text/css'>
body {<!--   w ww.  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