CSS hover触发下拉菜单时元素间距导致hover状态消失如何解决
问题原因
你当前写法的问题在于,.sub-menu设置的margin-top: 30px属于元素外间距,不属于父元素#dropdown的可响应hover区域,鼠标移动到这段空白时就脱离了#dropdown的hover范围,导致子菜单隐藏。
解决方案
以下两种方案都可以保留原有视觉间距,同时保证hover状态正常生效:
方案1:修改父元素内边距(最简实现)
给父元素#dropdown添加底部内边距,将空隙区域纳入父元素的hover范围,同时删除子菜单的margin-top即可,视觉效果完全不变:
#dropdown { text-align: center; padding-bottom: 30px; /* 新增 */ position: relative; /* 新增,保证子元素绝对定位相对父元素计算,避免布局偏移 */ } #dropdown .sub-menu{ visibility: hidden; position: absolute; background-color: black; left: 50%; transform: translateX(-50%); z-index: 1; width: 250px; /* margin-top: 30px; 移除这行 */ }
方案2:添加透明遮罩覆盖空隙
如果不想修改父元素的盒模型结构,可以给子菜单添加透明伪元素覆盖空隙区域,鼠标移到空隙时相当于悬停在子菜单上,不会触发hover失效:
#dropdown .sub-menu{ visibility: hidden; position: absolute; background-color: black; left: 50%; transform: translateX(-50%); z-index: 1; width: 250px; margin-top: 30px; } /* 新增伪元素样式 */ #dropdown .sub-menu::before { content: ""; position: absolute; top: -30px; left: 0; width: 100%; height: 30px; background: transparent; }
内容的提问来源于stack exchange,提问作者oldru27
相关产品推荐
相关产品推荐

