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

CSS实现鼠标悬停列表项左侧显示圆角竖线效果

问题根因

你当前代码的核心错误是直接修改悬停状态下li元素本身的宽度、背景属性,直接挤占了文本的排版空间,再叠加calc()语法错误(减号两侧必须加空格才能被正确解析)、没有适配多行列表项的高度,最终出现排版错乱、竖线显示异常的问题。

正确实现代码

不要直接改动li本身的盒模型来绘制竖线,改用::before伪元素绘制左侧指示线,伪元素通过绝对定位脱离文档流,完全不会干扰原有文本排版:

<html>
<style>
.table-of-contents{
  background-color:#F0FAFA;
  padding:48px;
  border-radius: 48px;
}
/* 给li设置相对定位,作为左侧竖线的定位基准 */
.table-of-contents li{
  position: relative;
  list-style: none;
  padding: 8px 0;
  padding-left: 20px;
}
/* 绘制左侧圆角竖线,默认隐藏 */
.table-of-contents li::before{
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 5px;
  height: 0;
  background-color:#785aff;
  border-radius:5px;
  transition: height 0.2s ease;
}
/* 悬停时竖线高度适配当前列表项的内容高度 */
.table-of-contents li:hover::before{
  height: calc(100% - 12px);
}
/* 可选:匹配设计稿的悬停文字变色效果 */
.table-of-contents li:hover a{
  color: #785aff;
}
.table-of-contents a{
  display: block;
  text-decoration: none;
  color: #333;
  line-height: 1.6;
}
</style>
<body>
<div class="table-of-contents">
<h2>Table of Contents</h2>
<ul style="margin:0; padding:0;">
    <li><a href="#">Link 1</a></li>
    <li><a href="#">Link 2</a></li>
    <li><a href="#">Link 3</a></li>
    <li><a href="#">This is a multiline url This is a multiline url This is a multiline url This is a multiline url This is a multiline url This is a multiline url This is a multiline url This is a multiline url This is a multiline url This is a multiline url This is a multiline url This is a multiline url </a></li>
</ul>
</div>
</body>
</html>
关键注意点
  • 伪元素绝对定位固定在列表项左侧,不占用文档流位置,单行、多行内容都不会出现排版挤压错乱的问题
  • 竖线通过垂直居中定位,悬停时高度自动匹配列表项实际内容高度,不需要手动给每个列表项设固定高度
  • 修正了原代码calc()的语法问题,CSS中calc()的运算符两侧必须加空格才能正常生效
  • 把list-style这类基础属性从hover状态移到li的默认样式中,避免状态切换时出现布局抖动

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 19:01:29