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

导航下拉菜单hover时仍偏移,如何统一父级与子级宽度?

导航菜单偏移与宽度不统一问题修复方案

当前导航存在两个核心问题:鼠标hover显示下拉菜单时出现偏移,以及父级按钮与子级下拉菜单宽度不一致。以下是针对这些问题的具体修复方案:

核心问题分析

  1. 原CSS中nav#nav-content>li使用position: absolute破坏了布局流,导致下拉菜单定位基准错误
  2. 下拉菜单采用position: relative会占据文档流空间,引发偏移
  3. 父级按钮与子菜单未设置统一宽度规则,导致宽度不一致

修复后的完整CSS代码

/***** whole navigation bar *****/

nav#nav-content {
  display: grid;
  place-items: center;
  font-family: "Gill Sans", sans-serif; /* 修正拼写错误font-faimily */
  font-size: 13.7px;
}

nav#nav-content ul {
  grid-auto-flow: column;
  list-style: none;
  text-align: center;
  padding: 0;
  margin: 0;
}

/* 改为相对定位作为下拉菜单的定位基准,移除绝对定位 */
nav#nav-content #exo-menu > li {
  position: relative;
  margin: 0;
  padding: 0;
  white-space: nowrap; /* 防止按钮文字换行 */
}

/***** all links *****/

ul#exo-menu a:link {
  display: block;
  text-decoration: none;
  background-color: #0E0E10;
  color: #FFFAFA;
  margin: 0;
  padding: 7px 13px;
  width: calc(100% - 26px); /* 抵消左右padding,保证整体宽度与父级一致 */
}

ul#exo-menu a:visited {
  background-color: #F5F5F5;
  color: #1A1110;
}

ul#exo-menu a:hover {
  background-color: #242124;
  color: #FFFFF0;
}

ul#exo-menu a:active {
  background-color: #D3D3D3;
  color: #808080;
}

/* disables links */

nav#nav-content div.cursor {
  cursor: not-allowed;
}

nav#nav-content a.disabledLink {
  pointer-events: none;
}

/***** all <button> tags *****/

button.dropbtn {
  outline: none;
  border: none;
  font: inherit;
  background-color: #0E0E10;
  color: #FFFAFA;
  padding: 7px 13px;
  cursor: pointer;
  margin: 0 5px;
  width: 100%; /* 按钮宽度占满父级li */
  text-align: left; /* 保持文字对齐 */
}

button.dropbtn:hover {
  background-color: #242124;
  color: #FFFFF0;
}

button.dropbtn:active {
  background-color: #D3D3D3;
  color: #808080;
}

/***** submenu positioning *****/

ul .dropdown {
  float: left;
  overflow: hidden;
}

#exo-menu ul {
  background-color: #0E0E10;
  color: #FFFAFA;
  position: absolute; /* 绝对定位脱离文档流,避免偏移 */
  top: 100%; /* 紧贴父级底部 */
  left: 0; /* 与父级左对齐 */
  display: none;
  width: 100%; /* 子菜单宽度继承父级li */
  padding: 0;
  margin: 0;
}

#exo-menu > li:hover > ul {
  display: block;
}

关键修改说明

  • 定位基准修正:将父级li的position: absolute改为relative,作为下拉菜单的定位容器,确保下拉菜单基于父级元素准确定位
  • 宽度统一处理:给按钮设置width: 100%占满父级空间,下拉菜单设置width: 100%继承父级宽度,同时调整子链接宽度抵消padding影响,保证整体宽度一致
  • 下拉定位修复:下拉菜单改用position: absolute,通过top:100%和left:0实现紧贴父级底部且左对齐,彻底解决偏移问题
  • 细节修正:修复font-faimily拼写错误,添加white-space: nowrap防止按钮文字换行破坏布局

HTML结构无需修改,直接替换上述CSS即可解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:10:38