HTML CSS JS
Стилизация Скролла
Дата размещения статьи 31/01/2020 👁61885
Стилизация Скролла
Стилизация Скролла
Сегодня будем стилизовать скролл с помощью CSS для webkit браузеров (Google Chrome / Safari / Opera / Яндекс.Браузер) и Mozilla Firefox. А так же рассмотрим изменение скролла при помощи плагина mCustomScrollbar.
Содержание:
- стилизация скролла для Firefox;
- стилизация скролла для остальных браузеров;
- кроссбраузерная стилизация с помощью плагина mCustomScrollbar;
- добавление скролла (принудительно);
- скрыть скролл, но оставить возможность прокрутки;
- CSS Scroll Snap;
- Scroll Snap Type;
- Scroll Snap Align;
- Scroll Snap со стрелками;
- примеры использования.
Стилизация скролла для Mozilla Firefox
Чтобы изменить скролл в Firefox, используйте следующий код.
html, body {
scrollbar-color: #458245 #714826; /* «цвет ползунка» «цвет полосы скроллбара» */
scrollbar-width: auto | thin | none; /* толщина */
}
Первое значение scrollbar-color изменяет цвет ползунка, второе — цвет скроллбара.
Значения scrollbar-width изменят толщину (ширину — для вертикального скроллбара, высоту — для горизонтального):
- auto — толщина скролла по умолчанию;
- thin — более тонкий вариант скролла;
- none — скрыть скролл.
Пример. Обратите внимание, данный пример предназначен для просмотра в Firefox.
Выберите цвет скроллбара
Выберите цвет ползунка скроллбара
Выберите толщину скролла
Какой-то контент. Текст, изображения или что-то ещё.
Стилизация скролла для webkit браузеров
Чтобы стилизовать скролл для Google Chrome, Яндекс.Браузер, Safari и Opera используйте следующие CSS свойства.
/* полоса прокрутки (скроллбар) */
::-webkit-scrollbar {
width: 24px; /* ширина для вертикального скролла */
height: 8px; /* высота для горизонтального скролла */
background-color: #143861;
}
/* ползунок скроллбара */
::-webkit-scrollbar-thumb {
background-color: #843465;
border-radius: 9em;
box-shadow: inset 1px 1px 10px #f3faf7;
}
::-webkit-scrollbar-thumb:hover {
background-color: #253861;
}
/* Стрелки */
::-webkit-scrollbar-button:vertical:start:decrement {
background: linear-gradient(120deg, #02141a 40%, rgba(0, 0, 0, 0) 41%),
linear-gradient(240deg, #02141a 40%, rgba(0, 0, 0, 0) 41%),
linear-gradient(0deg, #02141a 30%, rgba(0, 0, 0, 0) 31%);
background-color: #f6f8f4;
}
::-webkit-scrollbar-button:vertical:end:increment {
background:
linear-gradient(300deg, #02141a 40%, rgba(0, 0, 0, 0) 41%),
linear-gradient(60deg, #02141a 40%, rgba(0, 0, 0, 0) 41%),
linear-gradient(180deg, #02141a 30%, rgba(0, 0, 0, 0) 31%);
background-color: #f6f8f4;
}
::-webkit-scrollbar-button:horizontal:start:decrement {
background:
linear-gradient(30deg, #02141a 40%, rgba(0, 0, 0, 0) 41%),
linear-gradient(150deg, #02141a 40%, rgba(0, 0, 0, 0) 41%),
linear-gradient(270deg, #02141a 30%, rgba(0, 0, 0, 0) 31%);
background-color: #f6f8f4;
}
::-webkit-scrollbar-button:horizontal:end:increment {
background:
linear-gradient(210deg, #02141a 40%, rgba(0, 0, 0, 0) 41%),
linear-gradient(330deg, #02141a 40%, rgba(0, 0, 0, 0) 41%),
linear-gradient(90deg, #02141a 30%, rgba(0, 0, 0, 0) 31%);
background-color: #f6f8f4;
}
Теперь рассмотрим, как кроссбраузерно стилизовать скролл при помощи плагина mCustomScrollbar.
Сначала скачайте архив и извлеките к себе в проект файлы:
- jquery.mCustomScrollbar.min.css
- jquery.mCustomScrollbar.concat.min.js
- mCSB_buttons.png
Затем подключите jQuery и файлы плагина.
Или же можете подключить все файлы через CDN jsdelivr:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="//cdn.jsdelivr.net/jquery.mcustomscrollbar/3.0.6/jquery.mCustomScrollbar.min.css">
<script src="//cdn.jsdelivr.net/jquery.mcustomscrollbar/3.0.6/jquery.mCustomScrollbar.concat.min.js"></script>
Инициализация
Инициализация через JavaScript
(function ($) {
$(window).on("load", function () {
$(".mycustom-scroll").mCustomScrollbar();
});
})(jQuery);
Инициализация в HTML
<div class="mycustom-scroll" data-mcs-theme="3d-dark">
<!-- Ваш контент -->
</div>
Настройки
$(".mycustom-scroll").mCustomScrollbar({
axis: "y", // вертикальный скролл
theme: "rounded-dark", // тема
scrollInertia: "330", // продолжительность прокрутки, значение в миллисекундах
setHeight: "100%", // высота блока (переписывает CSS)
mouseWheel: {
deltaFactor: 300 // кол-во пикселей на одну прокрутку колёсика мыши
}
});
Темы mCustomScrollbar
Выбрать подходящую тему можно здесь.
Если же готовых тем недостаточно, то можете проинспектировать нужный элемент скролла и стилизовать как вам это необходимо.
Чтобы принудительно добавить скролл для блока, необходимо ограничить его по высоте/ширине и добавить overflow:
- overflow-y: auto; — для создания вертикального скролла (+ max-height);
- overflow-x: auto; — для создания горизонтального скролла (+ max-width).
При создании горизонтального скролла для текстового блока может понадобится добавление следующего css: white-space: nowrap;.
Скроем скролл, но оставим возможность прокрутки блока.
.el {
scrollbar-width: none; /* firefox */
}
.el::-webkit-scrollbar { /* webkit */
width: 0;
height: 0;
}
Позволяет прокручивать не попиксельно, а целыми блоками. Базовое использование.
<div class="parent-container">
<div class="children"></div>
<div class="children"></div>
<div class="children"></div>
<div class="children"></div>
</div>
.parent-container {
display: flex;
overflow-x: auto;
scroll-snap-type: x proximity;
}
.children {
scroll-snap-align: start;
}
Scroll Snap Type
Пример с горизонтальным Scroll Snap:
Вертикальный Scroll Snap.
.parent-container {
overflow-y: auto;
scroll-snap-type: x proximity;
}
.children {
scroll-snap-align: start;
}
Scroll Snap Align
Свойство Scroll Snap Align применяется к дочерним элементам контейнера, которые будем скролить. Мы можем указать какая сторона дочернего элемента будет прижата к родительскому блоку.
Примеры по оси X:
.parent-container {
display: flex;
overflow-x: auto;
scroll-snap-type: x proximity;
}
.children {
scroll-snap-align: start; /* start/center/end */
}
Примеры по оси Y:
.parent-container {
overflow-y: auto;
scroll-snap-type: y proximity;
}
.children {
scroll-snap-align: start; /* start/center/end */
}
Примеры использования Scroll Snap
Ниже приведены примеры использования Scroll Snap для реальных проектов.
Горизонтальный слайдер
.parent-container {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
}
.children {
scroll-snap-align: center;
}
Полноэкранная вертикальная прокрутка секций
.parent-container {
scroll-snap-type: y mandatory;
}
.children {
height: 100vh;
width: 100vw;
scroll-snap-align: start;
}
Полноэкранная горизонтальная прокрутка секций
.parent-container {
display: flex;
overflow-x: auto;
scroll-snap-type: x proximity;
}
.children {
height: 100vh;
width: 100vw;
scroll-snap-align: start;
}
Scroll Snap с навигацией
Реализуем Scroll Snap с навигацией, добавим стрелки для прокрутки.
Структура:
<div class="testimonials">
<div class="scroller">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
<span class="btn prev"><</span>
<span class="btn next">></span>
</div>
JavaScript:
const testimonials = document.querySelector(".testimonials");
const scroller = testimonials.querySelector(".scroller");
const nextBtn = testimonials.querySelector(".btn.next");
const prevBtn = testimonials.querySelector(".btn.prev");
const itemWidth = testimonials.querySelector(".item").clientWidth;
nextBtn.addEventListener("click", scrollToNextItem);
prevBtn.addEventListener("click", scrollToPrevItem);
function scrollToNextItem() {
if (scroller.scrollLeft < (scroller.scrollWidth - itemWidth)) {
// Позиция прокрутки не в начале последнего элемента
scroller.scrollBy({ left: itemWidth, top: 0, behavior: "smooth" });
} else {
// Достигнут последний элемент
// Вернёмся к первому элементу, установив положение прокрутки на 0
scroller.scrollTo({ left: 0, top: 0, behavior: "smooth" });
}
}
function scrollToPrevItem() {
if (scroller.scrollLeft != 0) {
// Позиция прокрутки не в начале первого элемента
scroller.scrollBy({ left: -itemWidth, top: 0, behavior: "smooth" });
} else {
// Это первый элемент (отзыв)
// Перейдём к последнему элементу, установив положение прокрутки на ширину «.scroller»
scroller.scrollTo({ left: scroller.scrollWidth, top: 0, behavior: "smooth" });
}
}
События Формы Отзывы в WordPress без Плагинов
Надеюсь, вам понравилась данная информация. Если вам интересна тема web-разработки,
то можете следить за выходом новых статей в Telegram.
- JavaScript: Работа с Массивами
- Наличие Динамически Добавленного Элемента
- Стилизация Input File
- Предзагрузка Картинок — Предварительная Загрузка Изображений на JavaScript
- События Формы
- Checkbox Checked — Проверка Состояния Чекбокса ✔️
Настройка полосы прокрутки (scrollbar) в основных браузерах была трудна и неприятна примерно до сентября 2018 года, когда был выпущен рабочий проект W3C CSS Scrollbars, который выглядит как реальный способ устранить трудности стилизации скроллбаров.
На протяжении многих лет появлялись различные способы сделать это. Microsoft Internet Explorer был одним из первых, кто предоставил CSS API для скроллбаров, но многие разработчики были настолько разочарованы реализацией, что создавали собственные решения с помощью JavaScript.
Однако, JavaScript-решения тоже не во всём идеальны, например им трудно эмулировать высокопроизводительное поведение, допустим, прокрутку с инерцией или прокрутку больших документов.
Перенесемся в настоящее время, теперь, когда Internet Explorer вытесняется Microsoft Edge, это сводится к двум подходам:
- Chrome/Edge/Safari используют
-webkit-scrollbar
- Firefox использует новую спецификацию CSS Scrollbars API (т.е.
scrollbar-color
иscrollbar-width
).
Давайте посмотрим на некоторые примеры кода!
Скроллбары в Chrome/Edge/Safari
В Chrome/Edge/Safari для стилизации прокрутки доступны css-свойства с вендорным префиксом -webkit-scrollbar
.
body::-webkit-scrollbar {
width: 12px; /* ширина scrollbar */
}
body::-webkit-scrollbar-track {
background: orange; /* цвет дорожки */
}
body::-webkit-scrollbar-thumb {
background-color: blue; /* цвет плашки */
border-radius: 20px; /* закругления плашки */
border: 3px solid orange; /* padding вокруг плашки */
}
Есть хорошие новости… И плохие новости…
Хорошие новости! Этот код прекрасно работает в последних выпусках Chrome/Edge/Safari!
Плохие новости. К сожалению, W3C официально отказалась от этой спецификации, поэтому можем ожидать в ближайшие годы её постепенное устаревание.
Скроллбары в Firefox
Firefox — чемпион в использовании новых стандартов W3C, они всегда готовы попробовать новые API. Таким образом, новые функции CSS Scrollbars уже доступны в обычных выпусках Firefox:
body {
scrollbar-width: thin; /* "auto" или "thin" */
scrollbar-color: blue orange; /* плашка скролла и дорожка */
}
Здесь легко заметить несколько различий по сравнению с устаревшей спецификацией --webkit-scrollbar
.
Во-первых, это лаконичный css-код! А во-вторых, в нём отсутствуют такие функции, как создание отступов и скруглений для плашки скролла. Поскольку спецификация всё ещё меняется, эти недостающие функции могут быть в неё включены.
Дальше-то, что?
Как стилизовать полосы прокрутки, с учётом отсутствия единого авторитетного API? Надо просто объединить оба подхода!
/* W3C standard
сейчас только для Firefox */
* {
scrollbar-width: thin;
scrollbar-color: blue orange;
}
/* для Chrome/Edge/Safari */
*::-webkit-scrollbar {
height: 12px;
width: 12px;
}
*::-webkit-scrollbar-track {
background: orange;
}
*::-webkit-scrollbar-thumb {
background-color: blue;
border-radius: 5px;
border: 3px solid orange;
}
Когда --webkit-scrollbar
устареет, можете спокойно вернуться к новому стандарту CSS Scrollbars.
See this code CSS scrollbar on x.xhtml.ru.
Вариант с использованием настраиваемых CSS-свойств (CSS-переменные). В этом случае появляется возможность управлять настройками CSS-свойств полосы прокрутки из Javascript, например, для управления темами:
See this code Styling scrollbars with CSS on x.xhtml.ru.
Ещё можно поэкспериментировать с CSS-градиентом, но этот вариант только для Webkit-браузеров:
See this code Styling scrollbars with CSS-gradient on x.xhtml.ru.
Custom Scrollbars In CSS
Стилизованные полосы прокрутки становятся популярными, думаю, вы
уже сталкивались с такими сайтами, которые имеют уникальный
скроллбар (к примеру, наш сайт). Есть два способа реализации этой задачи:
с помощью CSS3 или используя jQuery плагин. Мы будем использовать наиболее простой —
напишем CSS стили.
Примечание: стилизовать полосу прокрутки через -webkit префикс возможно только
в браузерах, использующих механизм рендеринга Webkit (и Blink). То есть в
Firefox и IE этот способ не сработает.
Часто бывает необходимо убрать или скрыть скроллбар css совсем. Для начала, давайте рассмотрим как это сделать.
Скрыть полосу прокрутки можно как у отдельного элемента на странице, так и у всей страницы целиком.
Сделать это не сложно, достаточно написать следующее свойство:
CSS
/*Убрать полосу прокрутки у элемента*/
.element::-webkit-scrollbar {
width: 0;
}
/*Убрать полосу прокрутки для всей страницы*/
::-webkit-scrollbar {
width: 0;
}
Теперь давайте рассмотрим базовую структуру полосы прокрутки:
-webkit-scrollbar состоит различных псевдо-элементов.
- ::-webkit-scrollbar — это фон самого скроллбара.
- ::-webkit-scrollbar-button — кнопки направления на полосе прокрутки.
- ::-webkit-scrollbar-track — пустое пространство под индикатором прокрутки.
- ::-webkit-scrollbar-thumb — индикатор прокрутки, перетаскиваемый элемент.
Проверим как все это работает. Чтобы попробовать изменить скроллбар css, создадим пустой HTML документ.
Вам необходимо добавить style.css ваш HTML файл. В разметку добавим div с id element, имеющий полосу прокрутки,
чтобы применить на него наши стили.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link type="text/css" rel="stylesheet" href="style.css">
</head>
<body>
<div id="element">
<div class="overflow"></div>
</div>
</body>
</html>
Для того, чтобы у элемента div появилась полоса прокрутки, добавим следующие свойства.
CSS
#element {
overflow-y: scroll;
background-color: #ffffff;
width: 200px;
height: 200px;
}
.overflow {
min-height: 400px;
}
Теперь давайте используем псевдоэлемент для создания пользовательского скроллбара.
Заменим ширину по умолчанию на новую — в 7 пикселей. Затем, добавим цвет полосы через свойство
background-color: #f9f9fd.
Если вы хотите изменить ширину скролла всей страницы, а не отдельного элемента,
то используйте ::-webkit-scrollbar без дополнительных селекторов.
CSS
#element::-webkit-scrollbar {
width: 7px;
background-color: #f9f9fd;
}
Мы уже знаем, что скроллбар состоит из полосы, кнопки и индикатора прокрутки.
Используем псевдо элемент ::-webkit-scrollbar-thumb, для того
чтобы стилизовать индикатор.
CSS
#element::-webkit-scrollbar-thumb {
background-color: #223c50;
}
Добавим свойство box-shadow полосе, чтобы добавить скроллбару контрастность.
Подобрать подходящую тень можно в нашем box-shadow генераторе.
CSS
#element::-webkit-scrollbar-track {
-webkit-box-shadow: 5px 5px 5px -5px rgba(34, 60, 80, 0.2) inset;
background-color: #f9f9fd;
}
В заключении: вот еще несколько вариантов, которые вы можете использовать на своем сайте.
Пример 1
#element::-webkit-scrollbar {
width: 10px;
background-color: #f9f9fd;
}
#element::-webkit-scrollbar-thumb {
border-radius: 10px;
background-color: #18aaaa;
}
#element::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.2);
border-radius: 10px;
background-color: #f9f9fd;
}
Пример 2
#element::-webkit-scrollbar {
width: 10px;
}
#element::-webkit-scrollbar-track {
-webkit-box-shadow: 5px 5px 5px -5px rgba(34, 60, 80, 0.2) inset;
background-color: #f9f9fd;
}
#element::-webkit-scrollbar-thumb {
background-color: #f2bf93;
background-image: -webkit-linear-gradient(45deg,rgba(255, 255, 255, .25) 25%,
transparent 25%,
transparent 50%,
rgba(255, 255, 255, .25) 50%,
rgba(255, 255, 255, .25) 75%,
transparent 75%,
transparent);
}
Пример 3
#element::-webkit-scrollbar {
width: 10px;
}
#element::-webkit-scrollbar-track {
-webkit-box-shadow: 5px 5px 5px -5px rgba(34, 60, 80, 0.2) inset;
background-color: #f9f9fd;
}
#element::-webkit-scrollbar-thumb {
background-color: #356184;
background-image: -webkit-gradient(linear, 0 0, 0 100%,
color-stop(.5, rgba(255, 255, 255, .25)),
color-stop(.5, transparent), to(transparent));
}
В четвертом примере мы используем градиент. Настроить его можно в CSS генераторе градиента.
Пример 4
#element::-webkit-scrollbar {
width: 10px;
}
#element::-webkit-scrollbar-track {
-webkit-box-shadow: 5px 5px 5px -5px rgba(34, 60, 80, 0.2) inset;
background-color: #f9f9fd;
border-radius: 10px;
}
#element::-webkit-scrollbar-thumb {
border-radius: 10px;
background: linear-gradient(180deg, #00c6fb, #005bea);
}
I styled my vertical scrollbars with the following code:
::-webkit-scrollbar {
width: 4px;
border: 1px solid #d5d5d5;
}
::-webkit-scrollbar-track {
border-radius: 0;
background: #eeeeee;
}
::-webkit-scrollbar-thumb {
border-radius: 0;
background: #b0b0b0;
}
Now, my vertical scrollbar looks like this:
However, my horizontal scrollbar looks like this :
How can I set a 2-4px height for it?
John Slegers
44k22 gold badges200 silver badges168 bronze badges
asked Jun 2, 2017 at 17:05
1
::-webkit-scrollbar {
height: 4px; /* height of horizontal scrollbar ← You're missing this */
width: 4px; /* width of vertical scrollbar */
border: 1px solid #d5d5d5;
}
since logically one cannot force a vertical scrollbar to be a certain height (since dictated by the positioned parent) — therefore such height
property is to target the horizontal’s scrollbar height — and vice-versa (width
for the width of the vertical scrollbar.).
answered Jun 2, 2017 at 17:22
Roko C. BuljanRoko C. Buljan
190k37 gold badges301 silver badges304 bronze badges
2
This may help
::-webkit-scrollbar{
height: 4px;
width: 4px;
background: gray;
}
::-webkit-scrollbar-thumb:horizontal{
background: #000;
border-radius: 10px;
}
answered Jun 2, 2017 at 17:46
Sifat HaqueSifat Haque
4,9791 gold badge15 silver badges22 bronze badges
::-webkit-scrollbar:horizontal{
height: 8px;
background-color: red;
}
::-webkit-scrollbar-thumb:horizontal{
background: #000;
border-radius: 10px;
}
answered Sep 9, 2021 at 10:19
1
Try This
::-webkit-scrollbar {
height: 8px;
overflow: visible;
width: 8px;
}
answered Jan 17, 2019 at 6:35
shrutishruti
1211 silver badge5 bronze badges
Just like @roco has noted above, since the vertical scroll bar’s height can not be modified then the height defined would be used for the horizontal bar, but using the -webkit-scrollbar
alone will solve your issue with the horizontal bar but will also make your vertical scroll bar behave abnormally, for the best result use this code,
::-webkit-scrollbar{
height: 4px;
width: 4px;
background: gray;
}
/* Track */
::-webkit-scrollbar-track {
background: #f1f1f1;
}
/* Handle */
::-webkit-scrollbar-thumb {
background: #888;
}
/* Handle on hover */
::-webkit-scrollbar-thumb:hover {
background: #555;
}
::-webkit-scrollbar-thumb:horizontal{
background: #000;
border-radius: 10px;
}
<!-- Just Focus with the CSS codes -->
<body style='width:200%'>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi at congue augue, sed dictum odio. Nunc imperdiet, lacus et consequat molestie, est lorem viverra mauris, id aliquet tortor purus vitae risus. In hac habitasse platea dictumst. Nulla ultrices fermentum maximus. Pellentesque accumsan condimentum finibus. Sed a mattis elit. Phasellus vel ullamcorper erat, eu euismod lorem. Nulla eu lorem ac mauris fringilla faucibus vel commodo ipsum.
Phasellus quis elementum dolor. Nulla dui nisl, ultrices et nulla pulvinar, placerat auctor libero. Morbi tristique vestibulum massa et varius. Donec posuere, nisl ac rutrum dictum, turpis tellus fringilla libero, ac feugiat elit metus ac augue. Nam justo turpis, blandit eget dui sit amet, molestie suscipit augue. Morbi erat velit, maximus a sem at, efficitur tempus mauris. In iaculis volutpat eros, vitae porttitor neque facilisis ac. Morbi ac maximus nunc. Fusce consectetur faucibus eros, nec aliquet nunc posuere vitae. Ut venenatis elementum lacus interdum finibus.
</p>
</body>
note: The -webkit-scrollbar is not supported in Firefox or in Edge, prior version 79.
answered Nov 8, 2021 at 21:01
AbdulbasitAbdulbasit
4848 silver badges12 bronze badges
Inside ::-webkit-scrollbar selected
, the height represents the horizontal scrollbar and the width represents the vertical scrollbar. You can also use :horizontal
psuedoclass.
answered Jun 23, 2020 at 13:48
Have you ever visited a website with a custom scrollbar and wondered how they did it? After reading this article you will understand just about everything there is to know about customizing and styling scrollbars using CSS.
In this tutorial you will:
- Learn the native CSS properties available for styling a scrollbar in the browser
- Create four unique scrollbars using CSS
- Learn about some external libraries that give cross-browser support for custom scrollbars
Video Tutorial
If you prefer video tutorials to reading, you can watch instead. You can also use the video to leave comments/questions and post links to your own custom scrollbars using something like CodePen so others can see your work.
Before jumping into the code, I think it’s worth looking at some potential tradeoffs that come with creating a custom scrollbar for your website or app.
The upside is that it can give your website a chance to standout compared to the millions of websites using the browser default scrollbar. Anything that can make your website even a little bit more memorable to visitors will benefit you long term.
On the other hand, many UI designers believe that you should never interfere with «standardized» UI components like the scrollbar. If you modify your scrollbar too much, it may confuse people using your website or app.
If you are doing this for your own personal website you probably don’t need to worry about it as long as you like how it looks.
On the other hand if you are thinking about implementing a custom scrollbar at work or some project where you want to make money, you should try A/B testing and make a data driven decision based on the results.
At the end of the day most of us are writing code to drive revenue for a business, so you always need to keep that in mind.
Getting Started
The first thing you need to do is create a basic layout so the page is large enough to actually show a scrollbar in your web browser:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel='stylesheet' href="styles.css">
<title>Document</title>
</head>
<body>
<div class="container">
<h1>CSS Scrollbar Customization</h1>
<p class="para">
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
</p>
<p class="para">
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
</p>
<p class="para">
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
</p>
<p class="para">
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
</p>
<p class="para">
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
</p>
<p class="para">
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
</p>
<p class="para">
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
</p>
<p class="para">
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
</p>
<p class="para">
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
</p>
<p class="para">
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
</p>
</div>
</body>
</html>
Nothing fancy here, just a basic div container with the class name container
for our layout, a header for a title, and a bunch of paragraphs with the class name para
to fill out our page.
Here’s the CSS to make things look a little fancier:
body {
font-family: Arial, Helvetica, sans-serif;
margin: 0;
}
.para {
font-size: 16px;
padding: 20px;
width: 70%;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
Your page should look something like this:
With our setup out of the way, we can jump into the fun part of the tutorial. The first part of this section will be learning the various CSS properties available to use for styling.
In the second part we’ll implement four different types of scrollbars to give you some ideas for making your own scrollbars.
CSS properties available for styling scrollbars
Unfortunately we still don’t have any standardized cross-browser support for styling scrollbars with CSS. Firefox and Webkit-based browsers like Chrome, Edge, and Safari have different properties for styling.
This tutorial will mainly focus on Webkit browsers, because they offer more options for styling, but we will briefly cover Firefox as well.
Webkit CSS styling properties for scrollbars
::-webkit-scrollbar
– the entire scrollbar::-webkit-scrollbar-track
– the entire progress bar area of the scrollbar::-webkit-scrollbar-thumb
– the draggable section of the scrollbar
The below properties are available but are less commonly used:
::-webkit-scrollbar-button
– the up/down buttons at each end of the scrollbar::-webkit-scrollbar-track-piece
– part of scrollbar not covered by the thumb::-webkit-scrollbar-corner
– bottom corner where horizontal and vertical scrollbars meet
Firefox CSS styling properties for scrollbars
There are currently two available CSS properties for styling scrollbars in Firefox
scrollbar-width
– controls width of scrollbar, with only two options available beingauto
orthin
scrollbar-color
– takes two colors which are used for the coloring of the thumb and track of the scrollbar in that order
Now that you know your options for customizing scrollbars, let’s put it into practice with some examples.
Dark Theme Scrollbar
Dark theme websites are all the rage right now. Sticking with the default browser scrollbar could come off as jarring to users because it doesn’t fit all that well with a dark themed website.
Let’s use our newfound knowledge of CSS to create a dark theme scrollbar with a rounded border inspired by CSS Tricks’ website:
html::-webkit-scrollbar {
width: 20px;
}
html::-webkit-scrollbar-track {
background-color: black;
}
html::-webkit-scrollbar-thumb {
background: #4e4e4e;
border-radius: 25px;
}
The result is a little hard to see in the screenshot, but the track is black and the thumb is a darkish gray color.
Minimalist Scrollbar
For this example you’ll be making a minimalist scrollbar. This type of scrollbar would work well if you are going for a simple, elegant style for your website.
The most important thing to note is that you have the ability to use hover
and active
pseudo-elements from CSS to further style your scrollbar. In this case the scrollbar will turn a darker gray when you hover and drag on the thumb.
html::-webkit-scrollbar {
width: 10px;
}
html::-webkit-scrollbar-track {
background: rgb(179, 177, 177);
border-radius: 10px;
}
html::-webkit-scrollbar-thumb {
background: rgb(136, 136, 136);
border-radius: 10px;
}
html::-webkit-scrollbar-thumb:hover {
background: rgb(100, 100, 100);
border-radius: 10px;
}
html::-webkit-scrollbar-thumb:active {
background: rgb(68, 68, 68);
border-radius: 10px;
}
The result:
Patterned Scrollbar
In this section, the focus is on using a repeating linear gradient to create a pattern effect on our scrollbar track. The same could be done for the scrollbar thumb as well.
Another thing to notice is that you can style the scrollbar thumb with a border, which you can use to create a number of cool effects. In this case I made the background color of the thumb transparent so that you can see the scrollbar track pattern as we scroll.
html::-webkit-scrollbar {
width: 20px;
}
html::-webkit-scrollbar-track {
background-image: repeating-linear-gradient(45deg, red 0, red 1px, transparent 0, transparent 50%);
background-size: 10px 10px;
}
html::-webkit-scrollbar-thumb {
background: transparent;
border-radius: 5px;
border: 2px solid black;
box-shadow: inset 1px 1px 5px black ;
}
The result:
«Animated» Gradient Scrollbar
This example uses a linear gradient and a trick with box shadow to make it look like the scrollbar is changing color as you move up and down the page. What’s really happening is that the background of the scrollbar track is being revealed beneath the thumb.
It works because the box-shadow takes up all the space of the scrollbar except for where the thumb is. Because the thumb is transparent the gradient color of the background shows through.
html::-webkit-scrollbar {
width: 20px;
}
html::-webkit-scrollbar-track {
background: linear-gradient(0deg, rgba(255, 0, 0, 1) 0%, rgba(7, 0, 211, 1) 100%);
}
html::-webkit-scrollbar-thumb {
background: transparent;
box-shadow: 0px 0px 0px 100vh black;
}
The result:
There are clearly some problems with creating custom scrollbars. The first would be the lack of cross-browser support. Other issues would be the lack of ability to add transitions or animations to the scrollbar and the fact your custom scrollbar won’t appear on mobile devices.
An alternative is hiding the default scrollbar and using a library, but this may effect performance when used as main scrollbar for your page. And there are other potential usability issues because these libraries rely on JavaScript to imitate the native scrollbar behavior.
Below I’ll go over two popular open-source libraries for making scrollbars.
SimpleBar Library
Grsmto/simplebar
Custom scrollbars vanilla javascript library with native scroll, done simple, lightweight, easy to use and cross-browser. — Grsmto/simplebar
GrsmtoGitHub
As the name tells you, SimpleBar is all about making it easy to create custom scrollbars. The only real downside here is that it doesn’t support usage as the main scrollbar for your website or for table, text area, or select HTML elements.
The main purpose of SimpleBar would be for creating custom scrollbars for things like dynamic chat applications or any other type of internal page element where you want scrolling.
Overlay Scrollbars Library
KingSora/OverlayScrollbars
A javascript scrollbar plugin which hides native scrollbars, provides custom styleable overlay scrollbars and keeps the native functionality and feeling. — KingSora/OverlayScrollbars
KingSoraGitHub
Overlay Scrollbars is very similar to SimpleBar but has the added benefit of supporting the HTML body element. This means that you can use it for the main scrollbar of your website in addition to all the other features you would expect like cross-browser and mobile support.
Conclusion
Hopefully this article gave you a solid understanding of how styling CSS scrollbars works.
If you have any questions you can leave a comment on the YouTube video and I’ll try to help you out. Also feel free to leave links to your own designs so other people can check them out.
Link to GitHub repo: https://github.com/renaissanceengineer/css-scrollbar-tutorial
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started