CSS свойство scrollbar
Используйте CSS-псевдоэлементы scrollbar для создания пользовательских тем полос прокрутки. Значения свойств и примеры.
Набор CSS псевдоэлементов ::-webkit-scrollbar — это проприетарный стилевой хук, позволяющий дизайнерам создавать пользовательские темы для встроенных полос прокрутки браузера.
Эти псевдоэлементы доступны через вендорный префикс -webkit и поддерживаются преимущественно в браузерах на основе Chromium. Они не поддерживаются в Firefox или Safari. Для более широкой поддержки браузеров рассмотрите использование стандартных свойств scrollbar-width и scrollbar-color.
Псевдоэлементы ::-webkit-scrollbar состоят из семи различных частей, которые вместе образуют полноценный элемент интерфейса полосы прокрутки. Эти семь псевдоэлементов следующие:
::-webkit-scrollbar::-webkit-scrollbar-button::-webkit-scrollbar-track::-webkit-scrollbar-track-piece::-webkit-scrollbar-thumb::-webkit-scrollbar-corner::-webkit-scrollbar-resizer
Полоса прокрутки появляется только тогда, когда содержимое элемента превышает размеры его блока, поэтому её стилизация тесно связана с семейством свойств overflow — overflow-x и overflow-y позволяют независимо управлять горизонтальной и вертикальной прокруткой.
Синтаксис
Для стилизации полос прокрутки CSS-правила применяются непосредственно к псевдоэлементам ::-webkit-scrollbar на прокручиваемом контейнере. Вы можете задавать стили любому элементу со значением overflow, равным scroll или auto, а не только body.
.scrolling-element::-webkit-scrollbar {
/* scrollbar styles */
}
.scrolling-element::-webkit-scrollbar-thumb {
/* thumb styles */
}Пример псевдоэлементов scrollbar:
Пример кода CSS scrollbar
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
html {
height: 100%;
overflow: hidden;
}
body {
height: 100%;
background: #eee;
overflow: scroll;
width: 85%;
max-width: 600px;
margin: 0 auto;
padding: 3em;
font: 100%/1.4 Georgia, serif;
border: 1px solid #666;
}
p {
margin: 0 0 1.5em;
}
body::-webkit-scrollbar {
width: 1em;
}
body::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
}
body::-webkit-scrollbar-thumb {
background-color: #666;
outline: 1px solid #eee;
}
</style>
</head>
<body>
<h2>Scrollbar property example</h2>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
</div>
</body>
</html>Пример псевдоэлементов scrollbar с ::-webkit-scrollbar-track и ::-webkit-scrollbar-thumb:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
html {
height: 100%;
overflow: hidden;
}
body {
height: 100%;
background: #ececec;
overflow: scroll;
width: 90%;
max-width: 550px;
margin: 0 auto;
padding: 2em;
border: 2px solid #cccccc;
}
p {
margin: 0 0 1.5em;
}
body::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
border-radius: 10px;
background-color: #F5F5F5;
}
body::-webkit-scrollbar {
width: 5px;
background-color: #F5F5F5;
}
body::-webkit-scrollbar-thumb {
border-radius: 10px;
-webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
background-color: #666666;
}
</style>
</head>
<body>
<h2>Scrollbar property example</h2>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
</div>
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
</div>
</body>
</html>Стандартные кроссбраузерные полосы прокрутки
Поскольку псевдоэлементы ::-webkit-scrollbar работают только в браузерах на основе Chromium, рабочая группа CSS ввела два стандартных свойства, которые Firefox поддерживает уже сегодня, а движки Webkit/Blink также начали их распознавать: scrollbar-width и scrollbar-color.
scrollbar-width— задаёт толщину. Принимает ключевые словаauto(по умолчанию),thinилиnone(скрывает полосу прокрутки, оставляя элемент прокручиваемым).scrollbar-color— принимает два цвета: сначала цвет ползунка, затем цвет дорожки.
.scrolling-element {
scrollbar-width: thin;
scrollbar-color: #666 #f5f5f5; /* thumb track */
}Надёжный подход — сначала объявить стандартные свойства в качестве базового уровня, а затем добавить поверх них правила ::-webkit-scrollbar для более тонкой настройки в браузерах Chromium, где это необходимо:
.scrolling-element {
/* Standard — Firefox and modern Chromium/Safari */
scrollbar-width: thin;
scrollbar-color: #666 #f5f5f5;
}
/* Detailed styling — Chromium-based browsers only */
.scrolling-element::-webkit-scrollbar {
width: 10px;
}
.scrolling-element::-webkit-scrollbar-track {
background: #f5f5f5;
}
.scrolling-element::-webkit-scrollbar-thumb {
background: #666;
border-radius: 10px;
}Используйте scrollbar-width: thin и scrollbar-color, когда нужно просто перекрасить или сузить полосу прокрутки во всех современных браузерах. Прибегайте к псевдоэлементам ::-webkit-scrollbar только тогда, когда требуется стилизовать отдельные части (кнопки, фрагмент дорожки, угол), недоступные стандартным свойствам. Скругление ползунка с помощью border-radius доступно только в -webkit- браузерах.
Псевдоэлементы
| Псевдоэлемент | Описание |
|---|---|
::-webkit-scrollbar | Сама полоса прокрутки. |
::-webkit-scrollbar-button | Кнопки на полосе прокрутки. |
::-webkit-scrollbar-track | Дорожка полосы прокрутки. |
::-webkit-scrollbar-track-piece | Часть дорожки, не перекрытая ползунком. |
::-webkit-scrollbar-thumb | Перетаскиваемый ползунок прокрутки. |
::-webkit-scrollbar-corner | Нижний угол полосы прокрутки, где пересекаются горизонтальная и вертикальная полосы. |
::-webkit-scrollbar-resizer | Перетаскиваемый маркер изменения размера, появляющийся в нижнем углу некоторых элементов. |