
css中的相邻兄弟选择器(adjacent sibling selector),由加号+表示,用于选择紧邻在指定元素之后的同级元素。其核心规则可以概括为两点:
例如,div + p会选择所有紧跟在div元素之后的p元素。
在实际开发中,开发者有时会遇到+选择器未能按预期工作的情况。这通常是因为对+选择器的“紧邻之后”这一特性理解不足。考虑以下示例,目标是当鼠标悬停在.container上时,显示.container-1元素:
原始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是同级元素,但.container-1在HTML结构中位于.container之前。根据+选择器的定义,它只能选择紧邻在指定元素之后的兄弟元素。因此,.container:hover + .container-1这个规则不会匹配到任何元素,导致.container-1始终保持display: none。
要使+选择器生效,最直接有效的方法是调整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样式(与之前相同,但现在会生效):
.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上时,display: block样式将成功应用到.container-1上,使其显示出来。
掌握+选择器的工作机制,并合理规划HTML结构,是编写高效、可维护CSS代码的关键。
以上就是解决CSS相邻兄弟选择器+不生效问题:理解其作用机制与HTML结构优化的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号