HTML & CSS – Styling Scrollbar

前言

Scrollbar 能 styling 的东西不多 (尤其是 IOS 基本上只能 display:none 而已),但有时候我们不得不 styling。

这里记入我自己在项目中修改过的 scrollbar 经历。

 

参考

can i use webkit-scrollbar

MDN – ::-webkit-scrollbar

MDN – scrollbar-width

MDN – scrollbar-color

 

例子

Gmail Scrollbar

Gmail 的 scrollbar 就改过 style (为了美观)。

size, color, border-radius 这几个地方都改过。

Ads Scrollbar

像这种可以 sticky vertical 的 scrollbar 是模拟出来的,但是它需要把 native scrollbar hide 起来,而且不可以使用 overflow hidden,因为虽然 scrollbar 要 hide 但是 touch move scroll 功能是要保留的,

所以只能通过 styling 的方式去 hide。

 

Styling Webkit Scrollbar (not Firefox, not IOS)

Chrome, Edge 会比较可以 styling scrollbar。FireFox,IOS 几乎不支持。

::webkit-scrollbar

.container {
  &::-webkit-scrollbar {
    height: 4px;       // for vertical scrollbar
    width: 4px;        // for horizontal scrollbar
    background-color: red; // for both
  }
}

修改 size, color。

它是透过伪元素 (pseudo-elements) 选择器来实现的,这也意味着我们无法透过 JS 来 styling scrollbar。

效果

红色的部分就是 scrollbar area。

也可以搭配 hover 才换颜色

.container {
  &::-webkit-scrollbar {
    background: transparent;
  }

  &::-webkit-scrollbar:hover {
    background: red;
  }
}

效果

如果想 hide scrollbar 可以设置 width 或 height = 0

::-webkit-scrollbar-thumb

.container {
  &::-webkit-scrollbar-thumb {
    border-radius: 999px;
  }

  &::-webkit-scrollbar-thumb:vertical {
    background-color: blue;
  }

  &::-webkit-scrollbar-thumb:horizontal {
    background-color: green;
  }
}

thumb 指的是我们拉动的区域,修改了 color 和 border-radius

提醒:那个 vertical 和 horizontal 伪类 (pseudo-classes) 选择器在 ::webkit-scrollbar 是不支持的哦。

效果

::-webkit-scrollbar-button

.container {
  &::-webkit-scrollbar-button:horizontal {
    background-color: purple;
  }
}

效果

 

Styling Firefox Scrollbar

Firefox 非常局限

.container {
  scrollbar-color: red orange; // first for thumb, second for track
  scrollbar-width: thin;       // 只能选 auto, thin, none
}

只能改 size 和 color,而且 size 只能选 auto, thin, none。

效果

这 2 个属性,Chrome 和 Edge 也支持,但 Safari 不支持。

 

Styling IOS Scrollbar

IOS 只支持下面这句

.container {
  &::-webkit-scrollbar {
    display: none;
  }
}

只能 display: none 其它都不支持。

 

 

总结

我个人的 Best Practice 是,只有 Chrome 和 Edge 可以 styling for 美观以外,Firefox 和 Safari 只能 styling for hide scrollbar。

 

posted @ 2024-05-06 13:55  兴杰  阅读(10)  评论(0编辑  收藏  举报