CSS滚动条美化及兼容

19,305 阅读2分钟

下面这个视频播放列表很长,使用 overflow: auto; 显示的是默认样式滚动条,其实也挺好看

image.png

但产品就是想优化一下,做成下面这种效果

image.png

怎么办?那就调一下呗,把他娘的意大利炮拉出来,不,把鼎鼎大名的 -webkit 请出来

webkit

这个列表盒子上有一个类.list-box

-webkit-scrollbar

  • 必须项
  • 作用:控制滚动条的宽度
.list-box::-webkit-scrollbar {
    width: 10px;
    // height: 10px; // 高度写不写,都不影响,因为会根据内容的长度自动计算
}

-webkit-scrollbar-thumb

  • 必须项
  • 作用:控制滚动条滑块的颜色、圆角、内阴影等
.list-box::-webkit-scrollbar {
    width: 10px;
    // height: 10px; // 高度写不写,都不影响,因为会根据内容的长度自动计算
}

.list-box::-webkit-scrollbar-thumb {
    background: #ccc; // 滑块颜色
    border-radius: 5px; // 滑块圆角
}

.list-box::-webkit-scrollbar-thumb:hover {
    background: #f40; // 鼠标移入滑块变红
}

image.png

-webkit-scrollbar-track

默认不显示滚动条的轨道

  • 非必须项
  • 作用:控制滚动条的轨道的圆角、内阴影等
.list-box::-webkit-scrollbar {
    width: 10px;
    // height: 10px; // 高度写不写,都不影响,因为会根据内容的长度自动计算
}

.list-box::-webkit-scrollbar-thumb {
    background: #ccc; // 滑块颜色
    border-radius: 5px; // 滑块圆角
}

.list-box::-webkit-scrollbar-thumb:hover {
    background: #f40; // 鼠标移入滑块变红
}

.list-box::-webkit-scrollbar-track {
    border-radius: 10px; // 轨道圆角
    background-color: #1890ff // 轨道颜色 
}

image.png

Firefox

scrollbar-width

scrollbar-color

IE

scrollbar-base-color

scrollbar-track-color

scrollbar-arrow-color

scrollbar-3dlight-color

scrollbar-shadow-color

scrollbar-highlight-color

全局滚动条样式美化

项目里一般都会有一个设置全局样式的less文件

// common.less
*::-webkit-scrollbar {
    width: 10px;
    // height: 10px; // 高度写不写,都不影响,因为会根据内容的长度自动计算
}

*::-webkit-scrollbar-thumb {
    background: #ccc; // 滑块颜色
    border-radius: 5px; // 滑块圆角
}

// 兼容Firefox、IE
* {
    scrollbar-width: 10px;
    scrollbar-base-color: green;
    scrollbar-track-color: red;
    scrollbar-arrow-color: blue;
}