
CSS的相邻兄弟选择器(+)是一个强大而常用的选择器,它允许我们选择紧邻在另一个指定元素之后的兄弟元素。理解其工作机制的关键在于以下几点:
在实际开发中,开发者有时会遇到使用+选择器实现hover效果时,样式不生效的问题。一个典型场景是,用户希望当鼠标悬停在某个元素上时,其“前一个”兄弟元素能够显示出来。
考虑以下原始的HTML和CSS代码:
原始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: block)。然而,实际效果是.container-1始终保持display: none,并没有按预期显示。
问题根源: 根据前面提到的+选择器的工作机制,container:hover + .container-1尝试选择的是紧邻在.container元素之后的.container-1元素。但在原始的HTML结构中,.container-1元素位于.container元素之前。由于选择器的方向性限制,它无法选择位于其之前的兄弟元素,因此样式规则无法匹配,导致.container-1元素不会在hover时显示。
解决这个问题的关键在于调整HTML元素的顺序,确保目标元素(.container-1)在触发元素(.container)之后,从而满足+选择器的匹配条件。
修改后的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);
}通过将<div class="container-1">移动到<div class="container">之后,现在它们是相邻的兄弟元素,并且.container-1紧随.container之后。这样,当鼠标悬停在.container上时,container:hover + .container-1选择器就能成功匹配到.container-1,并将其display属性设置为block,从而实现预期的显示效果。
CSS相邻兄弟选择器(+)是一个高效的工具,用于选择紧邻在特定元素之后的兄弟元素。其核心在于“单向性”、“兄弟关系”和“紧邻性”。当遇到+选择器不生效的情况时,首先应检查HTML元素的DOM顺序,确保目标元素确实位于触发元素之后。通过合理地组织HTML结构,我们可以充分利用+选择器,实现各种优雅的CSS交互效果。
以上就是深入理解CSS相邻兄弟选择器(+):工作原理与正确应用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号