如何缩短Scrollbar Track长度并居中适配圆角页面


这是我首次使用滚动条,希望将黄色标注的Scrollbar Track(滚动条轨道)缩短。当前页面带有圆角,滚动条超出页面范围显得突兀,我想将轨道上下两端稍作裁剪并在页面侧边居中。目前我的代码如下:
/* width */ ::-webkit-scrollbar { width: 15px; /* for vertical scrollbar */ } /* Handle */ ::-webkit-scrollbar-thumb { background: #888; border-radius: 10px; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: #666; } ::-webkit-scrollbar-track { background: yellow; height:40px; padding:5px 5px 5px 5px; }
给::-webkit-scrollbar-track设置height和padding对垂直滚动条不生效,换个思路就能实现需求:
实现步骤
- 给滚动容器(比如页面
body或指定的滚动容器)添加上下内边距,预留轨道缩进空间,同时设置background-clip: content-box避免背景延伸到内边距区域; - 给滚动条设置上下外边距,和容器内边距数值对应,让轨道居中;
- 按需调整轨道样式即可。
修改后的代码示例:
/* 针对页面滚动的情况,给body设置 */ body { padding: 20px 0; /* 上下内边距,数值决定轨道上下缩进的幅度 */ overflow-y: scroll; background-clip: content-box; } ::-webkit-scrollbar { width: 15px; margin: 20px 0; /* 上下外边距和body内边距保持一致,实现轨道居中 */ } ::-webkit-scrollbar-thumb { background: #888; border-radius: 10px; } ::-webkit-scrollbar-thumb:hover { background: #666; } ::-webkit-scrollbar-track { background: yellow; /* 如需给轨道加圆角,直接添加下面的属性 */ /* border-radius: 8px; */ }
如果是给特定容器设置滚动条,把代码中的body替换成你的容器选择器(比如.scroll-box)即可。
内容的提问来源于stack exchange,提问作者Lisa
相关产品推荐
相关产品推荐

