DEV Community

Lens
Lens

Posted on

How to make a custom scrollbar with CSS (2 ways)

Introduction

A few days ago i talked about how to create a custom cursor, so today i decided to also talk about how to create a custom scrollbar as well. It's pretty easy, but the reason why there's two ways is One of the ways are available for every browser but firefox, while the other can only be used by firefox.


Scrollbar Pseudo elements

An easy way to make a custom scroll bar is by using the psuedo element ::-webkit-scrollbar, there are also a variety a scrollbar psuedo-elements each for a specefic part of the scrollbar.

  • ::-webkit-scrollbar:horizontal stylizes the horizontal scrollbar specifically

  • ::-webkit-scrollbar:vertical stylizes the vertical scrollbar specifically

  • ::-webkit-scrollbar-track stylizes the scrollbar track, which contains the thumb (in other words it's the bar that contains the smaller scrolling bar)

  • ::-webkit-scrollbar-thumb stylizes the thumb, which is the bar that slides when scrolling

  • ::-webkit-scrollbar-button stylizes the buttons that make the thumb go up and down

As an example, i made a gradient horizontal scrollbar by stylizing the scrollbar thumb and giving a gradient background. I gave the track a light yellow background and gave the whole scrollbar a width of only 10px. You can see the code and the scrollbar down below!

/*To give the track a yellowish color*/
::-webkit-scrollbar-track {
background: #faedcd;
}

/*Shrinking the scrollbar*/
::-webkit-scrollbar {
  width: 10px;
}

/*Removing the horizontal scrollbar*/
::-webkit-scrollbar:horizontal {
  display: none;
}

/*Giving the thumb a gradient*/
::-webkit-scrollbar-thumb {
  background: linear-gradient(#4158D0, #C850C0, #FFCC70);
  border-radius: 20px;
}
Enter fullscreen mode Exit fullscreen mode



Browser Support

Not every browser supports these psuedo-elements. According to MDN web docs and caniuse.com the selectors a mostly supported in every browser except firefox. That's why on our next section we're going to talk about another way that's supportive for firefox.

browser suppor for psuedo elements


Scrollbar Properties

There are also two scrollbar properties that you can use to customize an element's or website's scrollbar. For example we can use the property scrollbar-color to change the color of the scrollbar. These properties only work using firefox and there's only two of them, so i even though i'm showing you this i suggest using the psuedo-elements instead since it has more of a variety in choices and availability!

  • scrollbar-width changes the width of the scrollbar
  • scrollbar-color changes the color of the scrollbar
body {
 scrollbar-width: 10px;
 scrollbar-color: linear-gradient(#FBAB7E, #F7CE68);
}
Enter fullscreen mode Exit fullscreen mode


Conclusion

I hope this blog helps you improve your css skills some more!

Top comments (0)