Css styling for scrollbar

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.

Источник

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-браузеров:

Источник

Guide to styling CSS scrollbars

Styling CSS Scrollbars Guide

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?

LogRocket Dashboard Free Trial Banner

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.

Источник

Читайте также:  jQuery Element Selector
Оцените статью