【CSS】动态修改浏览器滚动条宽度

发布于:2025-08-10 ⋅ 阅读:(23) ⋅ 点赞:(0)

完整源码

.container {
	  overflow: auto;
	  scrollbar-color: auto !important;
	  
	  &::-webkit-scrollbar {
	      background-color: transparent;
	      border-radius: 6px
	  }
	
	  &::-webkit-scrollbar:vertical {
	      width: 12px;
	      height: 8px
	  }
	
	  &::-webkit-scrollbar:horizontal {
	      width: 8px;
	      height: 12px
	  }
	
	  &::-webkit-scrollbar-thumb {
	      border-radius: 6px;
	      border: 4px solid transparent;
	      background-color: #ccc;
	      background-clip: content-box
	  }
}

在线效果演示

欢迎 Star 👏🏻 github 地址

原理分析

✅ 自定义 WebKit 滚动条(Chrome/Safari)

&::-webkit-scrollbar {
  background-color: transparent;
  border-radius: 6px;
}
  • 设置滚动条背景为透明。
  • 添加圆角(但这对整个滚动条轨道的圆角支持较有限)。
&::-webkit-scrollbar:vertical {
  width: 12px;
  height: 8px;
}
  • 垂直滚动条宽度为 12px。
  • height 对垂直滚动条其实无效,写了也不会生效。
&::-webkit-scrollbar:horizontal {
  width: 8px;
  height: 12px;
}

  • 水平滚动条高度为 12px。
  • width 对水平滚动条其实无效,写了也不会生效。

⚠️ 注意:width 和 height 实际只有一个维度起作用,另一个是冗余的。

✅ 滚动条滑块(thumb)样式

&::-webkit-scrollbar-thumb {
  border-radius: 6px;
  border: 4px solid transparent;
  background-color: #ccc;
  background-clip: content-box;
}

  • border-radius: 6px:让滑块圆角化。
  • border: 4px solid transparent:滑块周围加上透明边框。
  • background-color: #ccc:滑块主体颜色为浅灰色。
  • background-clip: content-box:让背景颜色只应用于实际内容区域(不覆盖透明边框),形成“内缩”效果,让滑块看起来更细。

在线效果演示
欢迎 Star 👏🏻 github 地址


网站公告

今日签到

点亮在社区的每一天
去签到