只在一个 div 中使用自定义滚动条

31

我想在Chrome中拥有自定义的滚动条。

因此,我正在使用以下Sass:

::-webkit-scrollbar {
  width: 0.5em;
  height: 0.5em;
}

::-webkit-scrollbar-thumb {
  background-color: rgba(255,255,255,.1);
  border-radius: 3px;

  &:hover {
    background: rgba(255,255,255,.2);
  }
}

我的问题是我只想在特定的 div 中使用这个滚动条样式。但如果我这样做:

#boardslist {

  ::-webkit-scrollbar {
    width: 0.5em;
    height: 0.5em;
  }

  ::-webkit-scrollbar-thumb {
    background-color: rgba(255,255,255,.1);
    border-radius: 3px;

    &:hover {
      background: rgba(255,255,255,.2);
    }
  }

}

无法正常工作。有任何想法吗?


3
你可以使用 fakeScroll(香草轻量级脚本)进一步自定义它。 - vsync
4个回答

45
#boardslist {

  &::-webkit-scrollbar {
   width: 0.5em;
   height: 0.5em;
  }

  &::-webkit-scrollbar-thumb {
   background-color: rgba(255,255,255,.1);
   border-radius: 3px;

   &:hover {
    background: rgba(255,255,255,.2);
   }
  }
}

看这个 http://codepen.io/tholman/pen/tldwm


1
但是在iOS Safari上似乎无法正确拖动滚动条(或单击箭头)。 - kiradotee
2
最好能够添加一个解释,说明为什么这样做有效。 - Corentin Pane

27

如果你是为了课程而这么做,可以按照以下方式进行。Side bar 是赋予想要允许滚动的div的类名。

.side_bar{
    padding-right: 20px; 
    margin-left: -12px;
    position: sticky;
    top: 0;
    height: 100vh;
    overflow-y: scroll;
    /* width */

}
.side_bar::-webkit-scrollbar {
        width: 5px;
    }

    /* Track */
.side_bar::-webkit-scrollbar-track {
        box-shadow: inset 0 0 2px grey; 
        border-radius: 10px;
    }

    /* Handle */
.side_bar::-webkit-scrollbar-thumb {
        background: rgb(7, 7, 7); 
        border-radius: 10px;
    }

    /* Handle on hover */
.side_bar::-webkit-scrollbar-thumb:hover {
        background: #009eb3; 
    }

2

现在是2020年,但是Firefox仍然不支持::-webkit-scrollbar。此外,在Chrome和Safari中,当内容溢出时,overflow:auto会显示滚动条,但在Firefox中,直到我们开始滚动,才会出现可见的滚动条。你需要猜测内容是否可滚动。对于overflow:scroll也是一样的。这并不是很直观。


2
2022年了,但是Firefox仍然没有支持:
https://caniuse.com/?search=%3A%3A-webkit-scrollbar

不过,在Firefox中可以自定义基础样式:
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Scrollbars
https://caniuse.com/?search=scrollbar-color

/* Chrome */
.container::-webkit-scrollbar {
    width: 5px;
}

.container::-webkit-scrollbar-track {
  /*background-color: grey;*/
  box-shadow: inset 0 0 5px grey; 
  border-radius: 15px;
}

.container::-webkit-scrollbar-thumb {
  background-color: orange; 
  border-radius: 15px;
  /*border: 1px solid red;*/
}

/*.container::-webkit-scrollbar-button {
  background-color: red;
   border-radius: 15px;
}*/

.container::-webkit-scrollbar-thumb:hover {
  background: red; 
}

/* IE */
.container {
  scrollbar-face-color: orange; 
  scrollbar-shadow-color: grey; 
  scrollbar-highlight-color: red;
}

/* FireFox */
.container {
  scrollbar-color: orange grey;
  scrollbar-width: thin;
}

/* View Scrollbar */
.container {
  overflow-y: scroll;
  overflow-x: hidden;
  width:400px;
  height: 200px;
}

这是一个工作示例:
https://codepen.io/svigir/pen/LYOOjyj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接