CSS hover触发Dropdown菜单不显示问题排查求助
问题:CSS hover无法触发Dropdown菜单显示
尝试通过CSS hover事件实现Dropdown菜单显示,但菜单始终无法触发显示。
HTML代码
<div> <button class="button button1"> Our Mission</button> <div class="dropdown"> <button class="button button3">What We Do</button> <div class="display_things"> <section class="column"> <table> <tr> <th>Our donations</th> </tr> <tr> <td><a>Event 1</a></td> </tr> <tr> <td><a>Event 2</a></td> </tr> <tr> <td><a>Event 3</a></td> </tr> </table> </section> <section class="column"> <table> <tr> <th>Our Community Work</th> </tr> <tr> <td><a>Event 1</a></td> </tr> <tr> <td><a>Event 2</a></td> </tr> <tr> <td><a>Event 3</a></td> </tr> </table> </section> </div> </div> <button class="button button4">Donate!</button> </div>
CSS代码
.button3 { background-color: #00ff9d; border: none; color: white; padding: 15px; text-align: center; text-decoration: none; display: inline-block; font-size: 20px; margin: 10px; border-radius: 20px; width:400px; white-space: nowrap; } .display_things { justify-content: space-around; margin: 10px; background-color: lawngreen; display: none; width: 1100px; position: absolute; } .button3:hover .display_things{ display: block; } .button4 { background-color: #f4740b; border: none; color: white; padding: 15px 170px; text-align: center; text-decoration: none; display: inline-block; font-size: 20px; margin: 10px; border-radius: 20px; width:400px; } .button:hover{ background-color: green; }
无法触发的原因
核心问题是CSS选择器匹配错误:
- 你写的
.button3:hover .display_things选择器,作用是选中.button3元素内部的子元素中拥有.display_things类的元素。 - 但实际HTML结构里,
.display_things和.button3是同级元素,共同嵌套在.dropdown容器中,并非父子关系,所以这个选择器无法匹配到目标元素,hover自然不会生效。
修复方案
有两种常用修复方式,推荐第一种(体验更友好):
方式1:通过父容器hover触发
将触发hover的选择器改为父容器.dropdown,这样鼠标悬停在按钮或菜单区域时,菜单都会保持显示:
.dropdown:hover .display_things{ display: flex; /* 因为你设置了justify-content,用flex更合适,也可以用block */ }
方式2:通过相邻兄弟选择器触发
如果只希望按钮hover时显示菜单(但鼠标移开按钮菜单会立即消失,体验较差),可以用相邻兄弟选择器+:
.button3:hover + .display_things{ display: flex; }
另外,.display_things设置了justify-content: space-around,但默认display: block不会生效,建议改为display: flex来启用flex布局,让两个column正确分布。
内容的提问来源于stack exchange,提问作者user17787294
相关产品推荐
相关产品推荐

