Color to scrollbars in css

CSS scrollbars styling

The CSS scrollbars styling module defines properties that you can use for visual styling of scrollbars. You can customize the width of the scrollbar as required. You can also customize the color of the scrollbar track, which is the background of the scrollbar, and the color of the scrollbar thumb, which is the draggable handle of the scrollbar.

Scrollbar styling in action

This example defines a thin scrollbar with a red thumb and an orange track. To view the thumb, you will need to scroll the text. After the scrollbar is visible, hover over it to see the track.

.poem  width: 300px; height: 100px; border: 1px solid; > 
.poem  overflow: scroll; scrollbar-color: red orange; scrollbar-width: thin; > 
blockquote class="poem"> h3>A Small Needful Facth3> pre> Is that Eric Garner worked for some time for the Parks and Rec. Horticultural Department, which means, perhaps, that with his very large hands, perhaps, in all likelihood, he put gently into the earth some plants which, most likely, some of them, in all likelihood, continue to grow, continue to do what such plants do, like house and feed small and necessary creatures, like being pleasant to touch and smell, like converting sunlight into food, like making it easier for us to breathe. pre > p> - a href="https://onbeing.org/poetry/a-small-needful-fact/">Ross Gaya> p> blockquote> 

Note: When customizing scrollbars, ensure that the thumb and track have enough contrast with the surrounding background. Also ensure that the scrollbar hit area is large enough for people who use touch input.

Reference

CSS properties

  • overflow-block CSS property
  • overflow-inline CSS property
  • overflow-x CSS property
  • overflow-y CSS property
  • overflow CSS shorthand property
  • overflow-clip-margin CSS property
  • scrollbar-gutter CSS property
  • scroll-behavior CSS property
  • scroll-margin CSS shorthand property
  • scroll-padding CSS shorthand property
  • scroll-snap-align CSS property
  • scroll-snap-stop CSS property
  • scroll-snap-type CSS property
  • ::-webkit-scrollbar pseudo-element
  • scroll container glossary term
  • scrollbar ARIA role

Specifications

See also

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

scrollbar-color

The scrollbar-color CSS property sets the color of the scrollbar track and thumb.

The track refers to the background of the scrollbar, which is generally fixed regardless of the scrolling position.

The thumb refers to the moving part of the scrollbar, which usually floats on top of the track.

When scrollbar-color value is set on the document’s root element, the values are applied to the viewport scrollbars.

Syntax

/* Keyword values */ scrollbar-color: auto; /* values */ scrollbar-color: rebeccapurple green; /* Two valid colors. The first applies to the thumb of the scrollbar, the second to the track. */ /* Global values */ scrollbar-color: inherit; scrollbar-color: initial; scrollbar-color: revert; scrollbar-color: revert-layer; scrollbar-color: unset; 

Values

Defines the color of the scrollbar.

auto Default platform rendering for the track portion of the scrollbar, in the absence of any other related scrollbar color properties.
Applies the first color to the scrollbar thumb, the second to the scrollbar track.

Accessibility concerns

When using scrollbar-color property with specific color values, authors should ensure the specified colors have enough contrast between them. For keyword values, UAs should ensure the colors they use have enough contrast. See Techniques for WCAG 2.0: G183: Using a contrast ratio of 3:1.

Formal definition

Источник

CSS: оформление скроллбаров 2022

Для максимально возможной кросс-браузерной поддержки стилизации полос прокрутки (scrollbar) лучше использовать специальные CSS-свойства с префиксом ::webkit (они понадобятся Chrome и Safari), а также стандартизированные свойства scrollbar-width и scrollbar-color (пока для Firefox).

Таким образом, базовая настройка будет выглядеть так:

.styled-scrollbars < /* плашка-бегунок и фон */ scrollbar-color: #999 #333; >.styled-scrollbars::-webkit-scrollbar < width: 10px; /* в основном для вертикальных полос прокрутки */ height: 10px; /* в основном для горизонтальных полос прокрутки */ >.styled-scrollbars::-webkit-scrollbar-thumb < /* плашка-бегунок */ background: #999; >.styled-scrollbars::-webkit-scrollbar-track < /* фон */ background: #333; >

Применение пользовательских CSS-свойств для стилизации скроллбаров

Это позволит вынести дублирующиеся значения CSS-свойств в настройки, например:

.styled-scrollbars < --scrollbar-foreground: #999; --scrollbar-background: #333; --scrollbar-size: 10px; /* плашка-бегунок, фон */ scrollbar-color: var(--scrollbar-foreground) var(--scrollbar-background); >.styled-scrollbars::-webkit-scrollbar < width: var(--scrollbar-size); /* в основном для вертикальных полос прокрутки */ height: var(--scrollbar-size); /* в основном для горизонтальных полос прокрутки */ >.styled-scrollbars::-webkit-scrollbar-thumb < /* плашка-бегунок */ background: var(--scrollbar-foreground); /* фон */ >.styled-scrollbars::-webkit-scrollbar-track < /* фон */ background: var(--scrollbar-background); >

Sass Mixin и другие опции предварительной обработки

При использовании Sass код может выглядеть следующим образом:

@mixin scrollbars( $size: 10px, $foreground-color: #999, $background-color: #333 ) < // для Chrome и Safari &::-webkit-scrollbar < width: $size; height: $size; >&::-webkit-scrollbar-thumb < background: $foreground-color; >&::-webkit-scrollbar-track < background: $background-color; >// по стандартам (Firefox) scrollbar-color: $foreground-color $background-color; >

Можно предположить, что с вендорными префиксами Autoprefixer может справиться лучше. Но это не будет хорошим решением, потому что синтаксис для каждого браузера будет очень сильно отличаться.

Если используется PostCSS, то для него есть плагин postcss-scrollbar . В коде используется стандартизированный синтаксис, а плагин делает соответствующие версии префиксов для разных браузеров.

После обработки плагином будет таким:

.scrollable::-webkit-scrollbar-thumb < background-color: yellow; >.scrollable::-webkit-scrollbar-track < background-color: green; >.scrollable::-webkit-scrollbar-corner < background-color: green; >.scrollable::-webkit-scrollbar < width: 0.5rem; height: 0.5rem; >.scrollable

Более экзотические стили скроллбаров в Chrome и Safari

В отличие от стандартизированных, префиксные ::-webkit- свойства имеют гораздо больше возможностей для стилизации полос прокрутки в CSS.

Например, ширину вертикальной полосы прокрутки можно сделать очень большой и добавить градиент:

Вот еще несколько стилей, в которых используется подход с вендорными префиксами:

Стилизация скроллбаров с помощью JavaScript

Если нужно очень детальное управление дизайном полос прокрутки в разных браузерах, то придется обратиться к решению вопроса с помощью JavaScript.

Для этого должны быть десятки библиотек. Например, simplebar выглядит довольно современным с простым созданием экземпляров. Вот демонстрация:

Пример кроссбраузерной стилизации полос прокрутки (scrollbar)

Это выглядит довольно прилично в Chrome, Safari и Firefox:

Источник

CSS: современный способ оформления скроллбаров

Настройка полосы прокрутки (scrollbar) в основных браузерах была трудна и неприятна примерно до сентября 2018 года, когда был выпущен рабочий проект W3C CSS Scrollbars, который выглядит как реальный способ устранить трудности стилизации скроллбаров.

изменить стиль scrollbar (полосы прокрутки)

На протяжении многих лет появлялись различные способы сделать это. 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 вокруг плашки */ >

scrollbar colors styling

Есть хорошие новости… И плохие новости…

Хорошие новости! Этот код прекрасно работает в последних выпусках Chrome/Edge/Safari!

Плохие новости. К сожалению, W3C официально отказалась от этой спецификации, поэтому можем ожидать в ближайшие годы её постепенное устаревание.

Скроллбары в Firefox

Firefox – чемпион в использовании новых стандартов W3C, они всегда готовы попробовать новые API. Таким образом, новые функции CSS Scrollbars уже доступны в обычных выпусках Firefox:

изменение цвета скроллбара в firefox

Здесь легко заметить несколько различий по сравнению с устаревшей спецификацией —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

Когда —webkit-scrollbar устареет, можете спокойно вернуться к новому стандарту CSS Scrollbars.

Вариант с использованием настраиваемых CSS-свойств (CSS-переменные). В этом случае появляется возможность управлять настройками CSS-свойств полосы прокрутки из Javascript, например, для управления темами:

Ещё можно поэкспериментировать с CSS-градиентом, но этот вариант только для Webkit-браузеров:

Источник

scrollbar-color

The scrollbar-color property controls the two colors of a scrollbar: the thumb color and the track color. scrollbar-color is part of the CSS Working Group’s Scrollbars Module Level 1 draft, which is still a work in progress as of this writing. Prior to scrollbar-color , developers had no standard way to change the default appearance of a browser’s scrollbars without resorting to hiding the scrollbar via overflow: hidden and rendering JavaScript-based scrollbars or using browser-prefixed scrollbar attributes. With scrollbar-color , on the other hand, we can style a scrollbar to match a design without resorting to redoing browser functionality or using vendor prefixes.

scrollbar with yellow track and red thumb

scrollbar-color will also accept values of dark and light to match a user’s preferences if they’re using something like dark mode on Mac OSX.

As of March 2019, support for dark and light values is not available in any browser. is supported in Firefox. See the browser support section below for details.

scrollbar-color: auto | dark | light | ;

scrollbar-color accepts the following values:

  • auto is the default value and will render the standard scrollbar colors for the user agent.
  • dark will tell the user agent to use darker scrollbars to match the current color scheme.
  • light will tell the user agent to use lighter scrollbars to match the current color scheme.
  • specifies two colors to be used for the scrollbar. The first color is for the “thumb” or the moveable part of the scrollbar which appears on top. The second color is for the “track” or the fixed portion of the scrollbar.

This combines the new spec syntax and the WebKit prefixed stuff.

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

Mobile / Tablet

Источник

Читайте также:  Convert sb3 to html
Оцените статью