W3docs

How to Select the Next Element in CSS

In this snippet, you can find out how to select the second element that directly follows the first one. For that, you need to use the adjacent sibling combinator (+).

Solution with the adjacent sibling combinator

The adjacent sibling combinator (+) is used to separate two selectors and match the second element only when it follows the first element immediately, and they have the same parent element.

In the following example, we use the adjacent sibling combinator to ensure that <p> element which follows the "example" of the <h1> element will use the CSS clear property with its "both" value.

Example of selecting the next element with the adjacent sibling selector:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      h1.example {
        float: left;
        font-size: 28px;
        color: #0d50bd;
        font-weight: bold;
        margin: 10px 0px;
      }
      h1.example + p {
        clear: both;
      }
    </style>
  </head>
  <body>
    <h1 class="example">Lorem Ipsum</h1>
    <p>
        Lorem Ipsum is simply dummy text of the printing and typesetting 
        industry. Lorem Ipsum has been the industry's standard dummy text 
        ever since the 1500s, when an unknown printer took a galley of 
        type and scrambled it to make a type specimen book.
    </p>
  </body>
</html>

Result

<div class="demo px-2.5 mt-1 mb-5 not-prose"> Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

</div>### Example of using the adjacent sibling combinator:

Example of using the adjacent sibling combinator:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      li:first-of-type + li {
        color: #00d42a;
      }
    </style>
  </head>
  <body>
    <ul>
      <li>First line</li>
      <li>Second line</li>
      <li>Third line</li>
    </ul>
  </body>
</html>