如果我们想要匹配紧跟在第一个选择器后出现的元素,我们可以使用相邻兄弟选择器(+)。在这里,两个选择器都是同一个父元素的子元素。
CSS相邻兄弟组合器的语法如下:
Selector + Selector{
attribute: /*value*/
}如果我们想选择同一父元素下的兄弟元素,不考虑第二个选定元素的位置,我们可以使用CSS通用兄弟选择器。
CSS通用兄弟选择器的语法如下:
Selector ~ Selector{
attribute: /*value*/
}下面的例子演示了CSS相邻和一般兄弟选择器属性。
立即学习“前端免费学习笔记(深入)”;
演示
<!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>这将产生以下结果 -

现场演示
<!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>这将产生以下结果 −

以上就是使用 CSS 选择同级元素的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号