
css相邻兄弟选择器(+)是一个非常有用的选择器,它允许我们选择紧接在另一个指定元素之后的同级元素。这里的“相邻”意味着紧密相连,而“兄弟”则表示它们共享同一个父元素。例如,div + p会选择所有紧跟在div元素之后的p元素。这个选择器常用于实现基于特定元素状态(如hover)来改变其相邻元素样式的效果,例如工具提示或菜单项的显示。
在实际开发中,开发者有时会遇到使用+选择器实现hover效果时,目标元素样式不生效的问题。以下是一个典型的示例:
原始HTML结构:
<div class="container-1">
<p><b>$167</b> still needed for this project</p>
</div>
<div class="container">
<div class="w3-light-grey" id="bar">
<div class="w3-orange" style="height: 18px;width:75%"></div>
</div>
<div class="box-1">
<p>
<span>
<b style="color:orange;">Only 3 days left</b> to fund this project
</span><br>
<span>
Join the <b>42</b> other donors who have already supported this project. Ever dollar helps.
</span>
</p>
<div>
<input type="text" class="field">
<input type="button" class="btn" value="Give Now"><br>
<span><b style="color:rgb(110, 200, 235);">Why give $50?</b></span>
</div>
</div>
</div>对应的CSS代码:
.container:hover + .container-1 {
display: block;
color:blue
}
.container-1{
display: none;
margin-bottom: 15px;
padding: 12px 0;
border-radius: 3px;
background-color: rgb(70, 70, 70);
}期望的效果是当鼠标悬停在.container元素上时,.container-1元素会从display: none变为display: block。然而,在上述代码中,无论如何悬停,.container-1元素始终保持隐藏状态。
立即学习“前端免费学习笔记(深入)”;
问题根源:+选择器的作用机制
问题的核心在于对+选择器工作原理的误解。+选择器用于选择紧接在指定元素 之后 的第一个兄弟元素。这意味着,如果我们要通过.container:hover + .container-1来匹配.container-1,那么在HTML文档结构中,.container-1必须紧跟在.container之后,并且两者必须是同级元素(拥有相同的父元素)。
回顾原始HTML结构,我们可以看到.container-1元素实际上位于.container元素 之前。CSS选择器是“向下”和“向后”查找的,它无法选择位于其参照元素之前的兄弟元素。因此,container:hover + .container-1这个选择器永远无法匹配到任何元素,因为在DOM中,.container后面没有紧邻的.container-1。
解决这个问题的关键在于调整HTML文档中元素的顺序,使其符合+选择器的匹配规则。
修正后的HTML结构:
<div class="container">
<div class="w3-light-grey" id="bar">
<div class="w3-orange" style="height: 18px;width:75%"></div>
</div>
<div class="box-1">
<p>
<span><b style="color:orange;">Only 3 days left</b> to fund this project</span>
<br>
<span>Join the <b>42</b> other donors who have already supported this project. Ever dollar helps.</span>
</p>
<div>
<input type="text" class="field">
<input type="button" class="btn" value="Give Now"><br>
<span><b style="color:rgb(110, 200, 235);">Why give $50?</b></span>
</div>
</div>
</div>
<div class="container-1">
<p><b>$167</b> still needed for this project</p>
</div>修正后的CSS代码(与原CSS相同):
.container:hover + .container-1 {
display: block;
color: blue;
}
.container-1 {
display: none;
margin-bottom: 15px;
padding: 12px 0;
border-radius: 3px;
background-color: rgb(70, 70, 70);
}原理阐释:
通过将.container-1元素移动到.container元素之后,它现在成为了.container的紧邻的下一个兄弟元素。当鼠标悬停在.container上时,container:hover + .container-1这个选择器就能成功匹配到.container-1,并将其display属性从none修改为block,从而实现了预期的显示效果。
CSS相邻兄弟选择器(+)是一个强大的工具,但其作用机制有明确的限制:它只能选择紧随其后的兄弟元素。理解这一点是避免常见布局问题、实现精确样式控制的关键。通过确保HTML文档中元素的正确相对顺序,开发者可以有效地利用+选择器来创建交互式的、响应式的网页设计。
以上就是深入理解与正确使用CSS相邻兄弟选择器(+)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号