对指定的元素应用 webkit 滚动条样式

我对以双冒号作为前缀的伪元素还是个新手。我偶然看到一篇博客文章,讨论使用 webkit 的 css 来设计滚动条的样式。伪元素 CSS 可以应用于单个元素吗?

/* This works by applying style to all scroll bars in window */
::-webkit-scrollbar {
width: 12px;
}


/* This does not apply the scrollbar to anything */
div ::-webkit-scrollbar {
width: 12px;
}

在这里,我希望对 div 的滚动条进行自定义,但是主窗口的滚动条保持默认状态。

Http://jsfiddle.net/mrtsherman/4xmub/1/

92874 次浏览

Your idea was correct. However, the notation div ::-webkit-scrollbar with a space after div is actually the same as div *::-webkit-scrollbar; this selector means "scrollbar of any element inside <div>". Use div::-webkit-scrollbar.

See demo at http://jsfiddle.net/4xMUB/2/

I want to use a class selector for using a custom scrollbar.

Somehow .foo::-webkit doesn't work, but I figured out that div.foo::-webkit does work! Those ##$$*## pseudo-things....

See http://jsfiddle.net/QcqBM/16/

You can also apply these rules by id of the element. Let's say scroll bar of a div has to be styled which has an id "myDivId". Then you can do following. This way you can use different styles for scroll bars of different elements.

#myDivId::-webkit-scrollbar {
width: 12px;
}


#myDivId::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
border-radius: 10px;
}


#myDivId::-webkit-scrollbar-thumb {
border-radius: 10px;
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.5);
}

http://jsfiddle.net/QcqBM/516/

You can have a scss file and apply the style to a class there

style.scss

.myscrollbar {
::-webkit-scrollbar {
width: 13px;
height: 13px;
}
::-webkit-scrollbar-thumb {
background: linear-gradient(13deg, #f9d4ff 14%, #c7ceff 64%);
border-radius: 10px;
}
::-webkit-scrollbar-thumb:hover {
background: linear-gradient(13deg, #c7ceff 14%, #f9d4ff 64%);
}
::-webkit-scrollbar-track {
background: #ffffff;
border-radius: 10px;
box-shadow: inset 7px 10px 12px #f0f0f0;
}
}

home.html

<div class="myscrollbar">
put your contents here
</div>

I used the scrollbar generator here: https://w3generator.com/scrollbar