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

如何消除菜单选项间的间距及CSS hover时的黑色分隔线?

导航菜单间距与hover线条问题解决方法

一、消除导航菜单选项之间的间距

导航项之间的空白是浏览器把inline/inline-block元素的换行、空格解析成空白字符导致的。最省心的解决方法是给导航容器#navbar启用flex布局:

#navbar {
  /* 保留原有样式,新增以下两行 */
  display: flex;
  justify-content: center;
  /* 删掉原来的上下padding,靠导航项自身的padding撑容器高度 */
  padding-top: 0;
  padding-bottom: 0;
}

flex布局会自动消除元素间的空白间距,同时还能轻松实现水平居中,比其他方法更简洁。

二、去除hover时菜单选项间的黑色线条

这个黑色线条其实是导航项之间的空白露出了navbar的黑色背景,解决上面的间距问题后线条自然会消失。另外要把自定义的<current>标签和<a>标签样式统一,避免hover时样式混乱:

/* 统一所有导航项的基础样式 */
#navbar a, #navbar current {
  color: #f2f2f2;
  text-align: center;
  padding: 12px 14px;
  text-decoration: none; /* 去掉默认下划线,提升视觉效果 */
  display: inline-block;
}

/* 统一hover状态样式 */
#navbar a:hover, #navbar current:hover {
  background-color: #ebebeb;
  color: black;
}

完整修改后代码

CSS

/* 可选:全局重置默认样式,避免浏览器自带margin/padding干扰 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* Style the navbar */
#navbar {
  overflow: hidden;
  background-color: #333;
  display: flex;
  justify-content: center;
}

/* Navbar links */
#navbar a, #navbar current {
  color: #f2f2f2;
  text-align: center;
  padding: 12px 14px;
  text-decoration: none;
  display: inline-block;
}

#navbar current {
  color: black;
  background-color: #ebebeb;
}

#navbar a:hover, #navbar current:hover {
  background-color: #ebebeb;
  color: black;
}

HTML

<div id="navbar">
  <current href="index.html">Home</current>
  <a href="about.html">About</a>
  <a href="services.html">Services</a>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:55:24