1. + selector

If you need to select an element immediately after another element and both have the same parent element, you can use the adjacent sibling selector.

Such as:

<style type="text/css">
    h1 + p {
        margin-top:50px;
        color:red;
    }
</style>


<body>
<p>This is paragraph.</p>
<h1>This is a heading.</h1>
<p>This is paragraph.</p>
<p>This is paragraph.</p>
Copy the code

The effect is as follows:

Note that the brothers will only remember the style of the p tag below, not affect the style of the brothers above. Note that the ‘+’ does not have the same meaning as the ‘and’. Sibling selectors are applied to sibling elements regardless of the style of the referenced element. In this example, they only affect the style of the P element, not the h1 tag. Of course, this will also loop, i.e. when two sibling elements are the same, it will loop once:

Example:

<style type="text/css">
    li + li {
        color:red;
    }
</style>

<div>
  <ul>
    <li>List item 1</li>
    <li>List item 2</li>
    <li>List item 3</li>
  </ul>
</div>
Copy the code



You can see that the first li is not red, but the second and third elements are red, because the third li is a sibling of the second Li, so styles are applied.

2. ~ selector

Finds all siblings of a specified element. The sample code

<style type="text/css">
    h1 ~ p{
        color:red;
    }
</style>
</head>
<body>
    <p>1</p>
    <h1>2</h1>
    <p>3</p>
    <p>4</p>
    <p>5</p>
</body>
Copy the code

Running results: