Sibling element selectors

The sibling or adjacent element selectors allow you to select elements that are at the same nesting level. Sometimes such elements are also called siblings or sister elements. For example:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sibling element selectors</title>
</head>

<body>
    <h2>Header</h2>
    <div>
        <p>First block text</p>
    </div>
    <div>
        <p>Second block text</p>
    </div>
</body>

</html>

Here the h2 elements and both divs are adjacent because they are on the same level. And the paragraph elements and the h2 heading are not contiguous because the paragraphs are nested in divs.

To style the first adjacent element relative to a specific element, use the plus sign +:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Selectors in CSS3</title>
    <style>
        h2+div {
            color: red;

        }
    </style>
</head>

<body>
    <h2>Header</h2>
    <div>
        <p>First block text</p>
    </div>
    <div>
        <p>Second block text</p>
    </div>
</body>

</html>

The selector h2+divallows you to define the style (in this case red text color) for the div that comes immediately after the h2 heading:

Moreover, this selector will style the div block if it comes directly after the heading. If there is another element between the header and the div blocks, then the style will not be applied to it, for example:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Selectors in CSS3</title>
    <style>
        h2+div {
            color: red;

        }
    </style>
</head>

<body>
    <h2>header</h2>
    <p>Element between header and div</p>
    <div>
        <p>The text of the first block</p>
    </div>
</body>

</html>

If we need to style all adjacent elements of the same level in general, whether they directly go after a certain element or not, then in this case, instead of the plus sign, we must use the tilde sign “~”:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Selectors in CSS3</title>
    <style>
        h2~div {
            color: red;
        }
    </style>
</head>

<body>
    <h2>header</h2>
    <p>Element between header and div</p>
    <div>
        <p>The text of the first block</p>
    </div>
</body>

</html>