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

如何用Tailwind CSS在侧边栏分类区域实现垂直滚动条

实现分类区域的自定义滚动条(类似YouTube风格)

核心思路

要实现仅分类区域滚动且匹配YouTube风格的滚动条,需要两步:

  • 给分类容器设置明确的高度限制,确保内容超出时触发滚动
  • 自定义滚动条样式,对齐YouTube的视觉效果

步骤1:调整分类容器的高度设置

你当前用了h-full,这会让容器继承父级高度,如果父级是整个侧边栏高度,就会导致整个侧边栏滚动。需要给分类容器设置最大高度,比如基于视口高度减去侧边栏其他元素的总高度(比如顶部标题、底部按钮等):

<div className="flex max-h-[calc(100vh-120px)] flex-col gap-5 overflow-y-auto scrollbar-custom">
  {categories.map((item) => (
    <NavLink
      to={`/category/${item.name}`}
      className={({ isActive }) => isActive ? isActiveStyle : isNotActiveStyle}
      onClick={handleCloseSidebar}
      key={item.name} {/* 用item.name做key比索引更可靠 */}
    >
      <img
        src={item.image}
        alt="category-item"
        className="w-8 h-8 rounded-full shadow-sm"
      />
      {item.name}
    </NavLink>
  ))}
</div>

提示:max-h-[calc(100vh-120px)]中的120px需要根据你侧边栏其他元素的实际总高度调整,确保分类容器只占用侧边栏的剩余空间。

步骤2:添加YouTube风格的自定义滚动条样式

在全局CSS文件(比如globals.css)中添加以下Tailwind兼容的自定义样式:

@layer utilities {
  .scrollbar-custom {
    scrollbar-width: thin; /* Firefox 滚动条宽度 */
    scrollbar-color: #888 transparent; /* Firefox 滚动条与轨道颜色 */
  }

  .scrollbar-custom::-webkit-scrollbar {
    width: 6px; /* 滚动条宽度,匹配YouTube的细窄风格 */
  }

  .scrollbar-custom::-webkit-scrollbar-track {
    background: transparent; /* 轨道透明 */
  }

  .scrollbar-custom::-webkit-scrollbar-thumb {
    background-color: #888; /* 默认滚动条颜色 */
    border-radius: 3px; /* 圆角设计 */
    transition: background-color 0.2s ease;
  }

  .scrollbar-custom::-webkit-scrollbar-thumb:hover {
    background-color: #aaa; /* hover时加深颜色 */
  }
}

这个样式实现了:

  • 细窄的滚动条(6px宽)
  • 透明轨道,hover时滚动条颜色动态加深
  • 圆角设计,完全对齐YouTube的滚动条视觉效果

关键注意事项

  • 必须给分类容器设置明确的高度/最大高度,否则overflow-y-auto不会生效
  • 如果侧边栏是固定定位,要确保容器高度计算考虑到侧边栏的padding和margin
  • 避免用索引作为列表key,用item.name这类唯一标识更可靠

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 14:02:08