- CSS: оформление скроллбаров 2022
- Применение пользовательских CSS-свойств для стилизации скроллбаров
- Sass Mixin и другие опции предварительной обработки
- Более экзотические стили скроллбаров в Chrome и Safari
- Стилизация скроллбаров с помощью JavaScript
- Пример кроссбраузерной стилизации полос прокрутки (scrollbar)
- Guide to styling CSS scrollbars
- Introduction to scrollbars
- Styling scrollbars in Chrome, Edge, and Safari
- Scrollbar pseudo-class selectors
- Styling scrollbars in Firefox
- Styling scrollbars for more cross-browser support
- Conclusion
- Is your frontend hogging your users’ CPU?
- How TO — Custom Scrollbar
- How To Create Custom Scrollbars
- Example
- Example
- Scrollbar Selectors
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:
Guide to styling CSS scrollbars
The default browser scrollbar works fine in most cases. However, leaving it as is can make even the most beautiful websites look incomplete and unpolished. By styling the scrollbar, you can create a more visually appealing site that better aligns with your brand or design. In this tutorial, we’ll explore a few different ways to style CSS scrollbars.
Introduction to scrollbars
The scrollbar is a frequently overlooked element in web design. While it may seem like a small detail, it plays an essential role in website navigation. The default scrollbar is often dull and might look out of place, detracting from the overall aesthetics. Fortunately, you can easily customize the scrollbar using CSS. To do so, you’ll need to write two sets of CSS rules to cover Webkit browsers, like Chrome, Edge, Safari, and Firefox.
Before diving into the code, let’s make sure we understand the structure of a scrollbar. Knowing this is helpful when styling it with CSS because you can use different properties to target specific parts of the scrollbar. Below are the elements that make up a scrollbar:
- Thumb: The movable part of the scrollbar that represents the current position of the content. It can be clicked and dragged to scroll the content up or down
- Track: The area of the scrollbar that the thumb moves along. It represents the entire length of the content
- Arrow buttons: Located at the top and bottom of the scrollbar track, the arrow buttons can be clicked to scroll the content
- Scrollbar borders: The lines that surround the scrollbar element
- Scrollbar corner: The intersection between the vertical and horizontal scrollbars when both are present
Styling scrollbars in Chrome, Edge, and Safari
Webkit browsers allow scrollbar styling using pseudo-elements like :: -webkit-scrollbar , ::-webkit-scrollbar-button , ::-webkit-scrollbar-thumb , ::-webkit-scrollbar-track , and more. Each of these targets different parts of the scrollbar, as listed above. The CodePen below shows an example of a styled scrollbar using the pseudo-elements above:
In the code above, we’ve displayed both the vertical and horizontal scrollbars, but in most cases, we’d only display one. To do so, we can modify the overflow property, which is responsible for the visibility of the scrollbar, to either overflow-x or overflow-y , depending on which axis we will display the scrollbar. However, for the example above, this wouldn’t be enough unless we make the image responsive by setting its width and height to 100% .
Scrollbar pseudo-class selectors
To create a more customized design, you can target specific elements of a scrollbar and apply styles to them by adding a pseudo-class to each pseudo-element. Below are some of the most common pseudo-classes:
- :horizontal : Used to style the horizontal scrollbar differently from the vertical scrollbar. For example, you can set a different width or color for the horizontal scrollbar
- :vertical : Used to style the vertical scrollbar differently from the horizontal scrollbar
- :decrement : Applies to the arrow buttons at the beginning of the scrollbar. It is used to style the decrement button or the up arrow for a vertical scrollbar and the left arrow for a horizontal scrollbar
- :increment : Applies to the arrow button at the end of the scrollbar. It is used to style the increment button or the down arrow for a vertical scrollbar and the right arrow for a horizontal scrollbar
- :start : Applies to the first buttons and first track piece of the scrollbar, which are at the top or left side of a vertical or horizontal scrollbar, respectively
- :end : Applies to the last track piece of the scrollbar, which are at the bottom or right side of a vertical or horizontal scrollbar, respectively
Below is an example that uses all the pseudo-classes above except :horizontal to give the vertical scrollbar a different look:
The example below uses the :horizontal pseudo-class to insert a shadow onto the horizontal scrollbar’s track:
While the Webkit specifications for styling a scrollbar work fine at the time of writing, W3C has officially abandoned this specification and it is expected to be phased out gradually.
Styling scrollbars in Firefox
Firefox doesn’t offer any advanced styling methods like the Webkit browsers. At the time of writing, only scrollbar-width and scrollbar-color are available, which is the standard as specified by W3C CSS Scrollbars. These properties can be used to style a scrollbar’s width, thumb, and track color:
Styling scrollbars for more cross-browser support
When styling a scrollbar, combining the Webkit and W3C CSS Scrollbars specifications is recommended to cover more browsers:
body < scrollbar-width: thin; scrollbar-color: #4d7fff #ddd; >body::-webkit-scrollbar < width: 10px; height: 10px; >body::-webkit-scrollbar-thumb < background: linear-gradient(to bottom right, #4d7fff 0%, #1a56ff 100%); border-radius: 5px; >body::-webkit-scrollbar-track < background-color: #ddd; border: 1px solid #ccc; >body::-webkit-scrollbar-button
In WebKit browsers, rules that aren’t recognized will be ignored, and the browsers will apply the -webkit-scrollbar rules. On the other hand, in Firefox browsers, rules that aren’t recognized will be ignored as well, and the browsers will apply the CSS scrollbars rules. Therefore, the scrollbar will retain its styling in more browsers. Although the downside is that there are no advanced styling methods in Firebox like in Webkit, you might be able to style the scrollbars to look exactly the same.
Conclusion
Styling a scrollbar makes a site look more polished. It can also help differentiate a brand or product by incorporating its color scheme or logo into the scrollbar design. However, it is recommended not to style your scrollbar too far from its original look and feel so as not to make it unfamiliar to users and reduce the user experience. I hope you enjoyed this article, and be sure to leave a comment if you have any questions. Happy coding!
Is your frontend hogging your users’ CPU?
As web frontends get increasingly complex, resource-greedy features demand more and more from the browser. If you’re interested in monitoring and tracking client-side CPU usage, memory usage, and more for all of your users in production, try LogRocket.https://logrocket.com/signup/
LogRocket is like a DVR for web and mobile apps, recording everything that happens in your web app, mobile app, or website. Instead of guessing why problems happen, you can aggregate and report on key frontend performance metrics, replay user sessions along with application state, log network requests, and automatically surface all errors.
Modernize how you debug web and mobile apps — Start monitoring for free.
How TO — Custom Scrollbar
Note: Custom scrollbars are not supported in Firefox or in Edge, prior version 79.
How To Create Custom Scrollbars
Chrome, Edge, Safari and Opera support the non-standard ::-webkit-scrollbar pseudo element, which allows us to modify the look of the browser’s scrollbar.
The following example creates a thin (10px wide) scrollbar, which has a grey track/bar color and a dark-grey (#888) handle:
Example
/* width */
::-webkit-scrollbar width: 10px;
>
/* Track */
::-webkit-scrollbar-track background: #f1f1f1;
>
/* Handle */
::-webkit-scrollbar-thumb background: #888;
>
/* Handle on hover */
::-webkit-scrollbar-thumb:hover background: #555;
>
This example creates a scrollbar with box shadow:
Example
/* width */
::-webkit-scrollbar width: 20px;
>
/* Track */
::-webkit-scrollbar-track box-shadow: inset 0 0 5px grey;
border-radius: 10px;
>
/* Handle */
::-webkit-scrollbar-thumb background: red;
border-radius: 10px;
>
Scrollbar Selectors
For webkit browsers, you can use the following pseudo elements to customize the browser’s scrollbar:
- ::-webkit-scrollbar the scrollbar.
- ::-webkit-scrollbar-button the buttons on the scrollbar (arrows pointing upwards and downwards).
- ::-webkit-scrollbar-thumb the draggable scrolling handle.
- ::-webkit-scrollbar-track the track (progress bar) of the scrollbar.
- ::-webkit-scrollbar-track-piece the track (progress bar) NOT covered by the handle.
- ::-webkit-scrollbar-corner the bottom corner of the scrollbar, where both horizontal and vertical scrollbars meet.
- ::-webkit-resizer the draggable resizing handle that appears at the bottom corner of some elements.