完整源码
css
.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)
css
&::-webkit-scrollbar {
background-color: transparent;
border-radius: 6px;
}
- 设置滚动条背景为透明。
- 添加圆角(但这对整个滚动条轨道的圆角支持较有限)。
css
&::-webkit-scrollbar:vertical {
width: 12px;
height: 8px;
}
- 垂直滚动条宽度为 12px。
- height 对垂直滚动条其实无效,写了也不会生效。
css
&::-webkit-scrollbar:horizontal {
width: 8px;
height: 12px;
}
- 水平滚动条高度为 12px。
- width 对水平滚动条其实无效,写了也不会生效。
⚠️ 注意:width 和 height 实际只有一个维度起作用,另一个是冗余的。
✅ 滚动条滑块(thumb)样式
css
&::-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 地址