You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让导航栏hover时展示的子菜单块与父元素保持相同宽度

问题根因

.sous-menu 开启了绝对定位,但它的直接父元素 #menu li 未设置 position: relative,导致绝对定位的子菜单找不到尺寸参考的祖先元素,默认相对于文档流定位,宽度自然无法和父菜单项对齐,另外还要注意清除ul默认的内边距、添加盒模型规则避免边框撑宽元素。

修复后完整CSS代码

* {
  box-sizing: border-box; /* 全局统一盒模型,边框内缩不撑宽,可根据需要调整作用范围 */
}
#menu{
    width: 60%;
    min-width: 500px;
    height: 20px;
    display: flex;
    justify-content: space-between;
    margin: 10px auto 15px auto;
    padding: 0; /* 清除ul默认内边距 */
}
#menu li{
    position: relative; /* 新增:作为子菜单绝对定位的参考 */
    width: calc(100% / 5 - 1%);
    min-width: 100px;
    height: 40px;
    display: block;
    list-style: none; /* 清除li默认圆点 */
}
#menu li a{
    width: 100%;
    height: 20px;
    display: block;
    background-color:#fff;
    font-family: Helvetica Constantia, "Lucida Bright", "DejaVu Serif", Georgia, "serif";
    font-size: 0.7em;
    line-height: 20px;
    color: #6E4712;
    border: 2px solid rgba(127,201,154, 0.5);
    text-align: center;
    text-decoration: none;
}
#menu li a:hover{
    color: rgba(127,201,154, 0.5);
}
#menu .sous-menu{ 
    display: none;
    margin-top: -2px;
    width: 100%; /* 新增:宽度和父li完全一致 */
    padding: 0; /* 清除子菜单ul默认内边距 */
}
#menu .sous-menu li{
    width: 100%;
    height: 20px;
    display: block;
}
#menu li:hover .sous-menu{ 
    display: block;
    position: absolute;
}

代码冗余优化建议

你当前代码中子菜单的a标签样式和父级完全一致,不需要重复定义,删掉#menu .sous-menu li a和#menu .sous-menu li a:hover两段重复代码即可,样式会自动继承父级定义的规则,后续调整统一样式也只需要修改一处。

内容的提问来源于stack exchange,提问作者Shalvus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 08:24:05