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

如何在响应式导航栏的两个元素之间添加居中分隔符?

实现带居中分隔符的等宽缩放导航栏

要实现每个链接项占导航栏33%,且分隔符居中在链接之间的效果,可以通过调整Flex布局和伪元素定位来实现,具体修改如下:

修改后的CSS代码

* {
  box-sizing: border-box;
}

nav {
  background-color: #333;
  padding: 10px;
}

ul {
  list-style: none;
  display: flex;
  align-items: center;
  padding: 0;
  margin: 0; /* 移除默认margin避免布局偏移 */
}

li {
  flex: 1; /* 让每个li平分导航栏宽度,自动占33%左右 */
  display: flex;
  justify-content: center; /* 让链接在li区块内居中 */
  position: relative; /* 为伪元素定位提供基准 */
}

/* 给前两个li添加右侧分隔符 */
li:not(:last-child):after {
  content: "|";
  color: white;
  position: absolute;
  right: 0; /* 定位到li的最右侧,刚好是两个li的分界处 */
  top: 50%;
  transform: translateY(-50%); /* 垂直居中 */
}

a {
  text-decoration: none;
  color: white;
  text-transform: uppercase;
}

nav ul li a:hover {
  text-decoration: underline;
}

HTML代码(无需修改)

<nav>
  <ul>
    <li><a href="#section1">link 1</a></li>
    <li><a href="#section2">link 2</a></li>
    <li><a href="#section3">link 3</a></li>
  </ul>
</nav>

关键说明

  1. 等宽布局:给每个<li>设置flex:1,三个li会自动平分导航栏的总宽度,实现每个链接区块占33%的需求,且随窗口大小自动缩放。
  2. 居中分隔符:利用li:not(:last-child):after伪元素,将分隔符定位在每个li的右侧边缘(即两个li的中间位置),通过transform: translateY(-50%)保证垂直居中,完全不影响链接本身的位置。
  3. 链接居中:每个li内部用justify-content: center让链接在自己的区块内居中,符合你期望的布局效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 03:45:10