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

如何实现头部导航主菜单横向排列并添加下拉子菜单

解决主菜单横向并排及下拉菜单显示问题

核心问题是导航栏的<ul>容器未设置横向布局,默认<li>作为块级元素会纵向排列,同时需要完善下拉菜单的隐藏/显示逻辑。以下是修改后的完整代码及说明:

修改后的CSS

* {
    text-decoration: none;
    list-style: none;
    margin: 0;
    padding: 0; /* 统一清除默认内外边距,避免布局偏差 */
}
body {
    margin: 0px;
    padding: 0px;
    font-family: roboto;
}
.header-text {
    position: relative;
    margin: 2px 6px 2px 4px;
    cursor: pointer;
}
.header-text h1 {
    font-size: 1.2rem; /* 缩小标题字号,适配header高度 */
    line-height: 30px; /* 和header高度一致,保证垂直居中 */
}
.header-icons {
    width: 32px;
    margin: 2px 0px 2px 0px;
    cursor: pointer;
}
header {
    display: flex;
    justify-content: space-between;
    background-color: rgb(20, 33, 61);
    color: white;
    height: 30px;
    align-items: center;
    padding: 6px;
    position: static;
}
/* 关键修改:让主菜单ul横向排列 */
.nav > ul {
    display: flex;
    gap: 12px; /* 控制菜单之间的间距 */
    align-items: center;
}
.nav li a {
    padding: 4px 8px;
    background-color: red;
    color: white; /* 添加文字颜色,避免与背景同色 */
}
/* 下拉菜单处理:默认隐藏,绝对定位避免影响主布局 */
.nav li ul {
    position: absolute;
    top: 42px; /* 对应header的高度30px+上下padding6px */
    background-color: rgb(20, 33, 61);
    display: none; /* 默认隐藏下拉菜单 */
}
.nav li:hover ul {
    display: block; /* 鼠标悬停父菜单时显示下拉项 */
}
.nav li ul li a {
    display: block; /* 下拉菜单项纵向排列 */
    white-space: nowrap; /* 防止文字换行 */
}

修改后的HTML

<header>
  <div class="header-text">
    <h1 class="titulo-logo">Lorem</h1>
  </div>

  <nav class="nav">
    <ul>
      <li><a href="">Notificaciones</a></li>
      <li>
        <a href="">Usuario</a>
        <ul>
          <li><a href="">Mi Perfil</a></li> <!-- 修正原HTML中a标签闭合错误 -->
        </ul>
      </li>
    </ul>
  </nav>
</header>

关键修改点说明

  • 给导航主<ul>添加display: flex,让子<li>横向并排,用gap控制菜单间距
  • 修复原HTML中<a href=""></a>Mi Perfil的标签错误,将文字放入<a>标签内部
  • 为下拉菜单设置绝对定位,默认隐藏,鼠标悬停父菜单时显示,避免干扰主布局高度
  • 统一清除所有元素的默认内外边距,消除浏览器默认样式的布局干扰
  • 调整标题字号和行高,适配header高度,保证标题垂直居中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:45:34