Home > Web Front-end > CSS Tutorial > Select sibling elements using CSS

Select sibling elements using CSS

WBOY
Release: 2023-09-13 09:53:05
forward
1276 people have browsed it

If we want to match elements that appear immediately after the first selector, we can use the adjacent sibling selector ( ). Here, both selectors are children of the same parent element.

The syntax of CSS adjacent sibling combinator is as follows:

Selector + Selector{
   attribute: /*value*/
}
Copy after login

If we want to select sibling elements under the same parent element, regardless of the position of the second selected element, we can use CSS Universal sibling selector.

The syntax of CSS universal sibling selector is as follows:

Selector ~ Selector{
   attribute: /*value*/
}
Copy after login

The following example demonstrates CSS adjacent and general sibling selector properties.

Example

Demonstration

<!DOCTYPE html>
<html>
<head>
<style>
#parent {
   display: flex;
   margin: 2%;
   padding: 2%;
   box-shadow: inset 0 0 24px cyan;
   justify-content: space-around;
}
div + p {
   font-size: 1.2em;
   font-weight: bold;
   background: powderblue;
}
section {
   box-shadow: 0 0 3px rgba(0,0,0,0.8);
}
</style>
</head>
<body>
<div id="parent">
<img src="https://i.picsum.photos/id/616/200/200.jpg?hmac=QEzyEzU6nVn4d_vdALhsT9UAtTU
EVhwrT-kM5ogBqKM" />
<div>
<p>Check this</p>
<section><p>Some text in section</p></section>
<span>hello</span>
</div>
<p>Selected</p>
</div>
</body>
</html>
Copy after login

Output

This will produce the following results -

使用 CSS 选择同级元素

Example

Live Demonstration

<!DOCTYPE html>
<html>
<head>
<style>
#parent {
   display: flex;
   margin: 2%;
   padding: 2%;
   background: thistle;
   justify-content: space-between;
}
section ~ p {
   text-align: center;
   font-size: 1.2em;
   font-weight: bold;
   background: lavender;
}
</style>
</head>
<body>
<div id="parent">
<img src="https://i.picsum.photos/id/616/200/200.jpg?hmac=QEzyEzU6nVn4d_vdALhsT9UAtTU
EVhwrT-kM5ogBqKM" />
<div>
<p>Random text 1</p>
<section><p>Some text in section</p></section>
<span>hello</span>
<p>Selected</p>
</div>
<img src="https://i.picsum.photos/id/1035/200/200.jpg?hmac=IDuYUZQ_7a6h4pQU2k7p2nxTMjMt4uy-p3ze94KtA4" />
</div>
</body>
</html>
Copy after login

Output

This will produce the following results−

使用 CSS 选择同级元素

The above is the detailed content of Select sibling elements using CSS. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template