How Does the CSS Adjacent Sibling Combinator ( ) Work?

Barbara Streisand
Release: 2024-10-30 02:04:29
Original
739 people have browsed it

How Does the CSS Adjacent Sibling Combinator ( ) Work?

Understanding the CSS Adjacent Sibling Combinator:

In CSS, the symbol is known as the adjacent sibling combinator. It allows you to target specific HTML elements that are positioned adjacent to each other.

How Does the Combinator Work?

The combinator ensures that the targeted element (the second element in the selector) must follow the first element (the first element in the selector) immediately. There should be no other elements in between the two elements for the selector to match.

Example: h2 p

Consider the following CSS rule:

<code class="css">h2 + p {
  font-size: 1.4em;
  font-weight: bold;
  color: #777;
}</code>
Copy after login

This rule targets all p elements that are adjacent to h2 elements. In other words, it will only affect p elements that appear immediately after h2 elements.

Illustration

Take this HTML code as an example:

<code class="html"><h2>Headline!</h2>
<p>The first paragraph.</p> <!-- Selected -->
<p>The second paragraph.</p> <!-- Not selected -->

<h2>Another headline!</h2>
<blockquote>
    <p>A quotation.</p> <!-- Not selected -->
</blockquote></code>
Copy after login

Only the first p element will be selected by the h2 p selector because it is adjacent to an h2. The second p element is not selected because it is separated from the h2 by a

. The p element within the blockquote is also not selected because there is no h2 element immediately preceding it within the same block.

Distinction from the General Sibling Combinator ~

Unlike the combinator, the general sibling combinator ~ does not require adjacent placement. It selects elements that are siblings, regardless of their position in relation to each other.

The above is the detailed content of How Does the CSS Adjacent Sibling Combinator ( ) Work?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!