CSS - 相邻兄弟选择器
CSS 中的相邻兄弟选择器
CSS 相邻兄弟选择器或下一个兄弟选择器用于选择紧跟在另一个元素之后的元素。它仅用于选择紧跟第一个选择器之后的那些元素。两个元素应共享同一个父元素。
语法
CSS 相邻兄弟选择器的语法如下:
selector1 + selector2 {
/* 属性: 值; */
color: #04af2f
}
相邻兄弟选择器的示例
在这个示例中,样式仅应用于紧跟在 div 元素之后的 p 元素。其他 p 元素不受影响。
<!DOCTYPE html>
<html lang="en">
<head>
<style>
div{
border: 2px solid #031926;
}
div + p {
color: #04af2f;
}
</style>
</head>
<body>
<p>
This paragraph is above the div
and will not be green.
</p>
<div>
<p>
This paragraph is inside a div
and will not be green..
</p>
</div>
<p>
This paragraph 1 after the div
and will be green..
</p>
<p>This paragraph 2 after the
div and will not be green..
</p>
</body>
</html>
示例 2
在这个示例中,我们使用相邻兄弟选择器来设计紧跟在具有相同父元素(即 div container)的 h3 标签之后的 p 元素。
<!DOCTYPE html>
<html>
<head>
<style>
.container {
padding: 20px;
border: 2px solid #031926;
font-family: Verdana, sans-serif;
}
h3 + p {
font-family: Verdana, sans-serif;
font-size: 20px;
font-style: italic;
background-color: #04af2f;
color: white;
}
</style>
</head>
<body>
<div class="container">
<h3>This is an h3 tag</h3>
<p>
This is a p tag that immediately follows the h3 tag.
</p>
<p>
This is another p tag, but it does not immediately
after the h3 tag.
</p>
</div>
<p>This is a p tag which is outside the parent div element.</p>
</body>
</html>