Как изменить скроллбар css

Как стилизовать или убрать полосу прокрутки — CSS скроллбар

Как стилизовать или убрать полосу прокрутки — CSS скроллбар

Стилизованные полосы прокрутки становятся популярными, думаю, вы уже сталкивались с такими сайтами, которые имеют уникальный скроллбар (к примеру, наш сайт). Есть два способа реализации этой задачи: с помощью CSS3 или используя jQuery плагин. Мы будем использовать наиболее простой — напишем CSS стили.

полоса прокрутки css

Часто бывает необходимо убрать или скрыть скроллбар css совсем. Для начала, давайте рассмотрим как это сделать.

1 Как убрать полосу прокрутки CSS

Скрыть полосу прокрутки можно как у отдельного элемента на странице, так и у всей страницы целиком. Сделать это не сложно, достаточно написать следующее свойство:

2 Как изменить скроллбар CSS

Теперь давайте рассмотрим базовую структуру полосы прокрутки:

стилизация полосы прокрутки

-webkit-scrollbar состоит различных псевдо-элементов.

  1. ::-webkit-scrollbar — это фон самого скроллбара.
  2. ::-webkit-scrollbar-button — кнопки направления на полосе прокрутки.
  3. ::-webkit-scrollbar-track — пустое пространство под индикатором прокрутки.
  4. ::-webkit-scrollbar-thumb — индикатор прокрутки, перетаскиваемый элемент.

Проверим как все это работает. Чтобы попробовать изменить скроллбар css, создадим пустой HTML документ. Вам необходимо добавить style.css ваш HTML файл. В разметку добавим div с id element, имеющий полосу прокрутки, чтобы применить на него наши стили.

3 CSS стили

Для того, чтобы у элемента div появилась полоса прокрутки, добавим следующие свойства.

Теперь давайте используем псевдоэлемент для создания пользовательского скроллбара. Заменим ширину по умолчанию на новую — в 7 пикселей. Затем, добавим цвет полосы через свойство background-color: #f9f9fd .

Мы уже знаем, что скроллбар состоит из полосы, кнопки и индикатора прокрутки. Используем псевдо элемент ::-webkit-scrollbar-thumb , для того чтобы стилизовать индикатор.

Добавим свойство box-shadow полосе, чтобы добавить скроллбару контрастность. Подобрать подходящую тень можно в нашем box-shadow генераторе.

В заключении: вот еще несколько вариантов, которые вы можете использовать на своем сайте.

Стилизация Скролла

Сегодня будем стилизовать скролл с помощью CSS для webkit браузеров (Google Chrome / Safari / Opera / Яндекс.Браузер) и Mozilla Firefox. А так же рассмотрим изменение скролла при помощи плагина mCustomScrollbar.

Стилизация скролла для Mozilla Firefox

Чтобы изменить скролл в Firefox, используйте следующий код.

Первое значение scrollbar-color изменяет цвет ползунка, второе — цвет скроллбара.

Стилизация скролла в Mozilla Firefox

Значения scrollbar-width изменят толщину (ширину — для вертикального скроллбара, высоту — для горизонтального):

  • auto — толщина скролла по умолчанию;
  • thin — более тонкий вариант скролла;
  • none — скрыть скролл.

Пример. Обратите внимание, данный пример предназначен для просмотра в Firefox .

Выберите цвет скроллбара
Выберите цвет ползунка скроллбара
Выберите толщину скролла

Какой-то контент. Текст, изображения или что-то ещё.

Стилизация скролла для webkit браузеров

Чтобы стилизовать скролл для Google Chrome, Яндекс.Браузер, Safari и Opera используйте следующие CSS свойства.

mCustomScrollbar

Теперь рассмотрим, как кроссбраузерно стилизовать скролл при помощи плагина mCustomScrollbar.

Сначала скачайте архив и извлеките к себе в проект файлы:

  • jquery.mCustomScrollbar.min.css
  • jquery.mCustomScrollbar.concat.min.js
  • mCSB_buttons.png

Затем подключите jQuery и файлы плагина.

Или же можете подключить все файлы через CDN jsdelivr:

Инициализация

Инициализация через JavaScript
Инициализация в HTML

Настройки

Темы mCustomScrollbar

Выбрать подходящую тему можно здесь.

Если же готовых тем недостаточно, то можете проинспектировать нужный элемент скролла и стилизовать как вам это необходимо.

Добавление скролла

Чтобы принудительно добавить скролл для блока, необходимо ограничить его по высоте/ширине и добавить overflow :

  • overflow-y: auto; — для создания вертикального скролла (+ max-height);
  • overflow-x: auto; — для создания горизонтального скролла (+ max-width).

При создании горизонтального скролла для текстового блока может понадобится добавление следующего css: white-space: nowrap; .

Как скрыть скролл

Скроем скролл, но оставим возможность прокрутки блока.

CSS Scroll Snap

Позволяет прокручивать не попиксельно, а целыми блоками. Базовое использование.

CSS Scrollbar Styling Tutorial – How to Make a Custom Scrollbar

Charles M.

Charles M.

CSS Scrollbar Styling Tutorial – How to Make a Custom Scrollbar

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.

Pros and Cons of a Custom Scrollbar

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:

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:

Your page should look something like this:

layout-preview

How to Create Custom Scrollbars with CSS

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 being auto or thin
  • 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:

The result is a little hard to see in the screenshot, but the track is black and the thumb is a darkish gray color.

dark-theme

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.

minimalist

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.

patterned

«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.

animated

Custom Scrollbar Limitations and Alternatives

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

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

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.

How can I style horizontal scrollbar by CSS?

I styled my vertical scrollbars with the following code:

Now, my vertical scrollbar looks like this:

enter image description here

However, my horizontal scrollbar looks like this :

enter image description here

How can I set a 2-4px height for it?

John Slegers's user avatar

6 Answers 6

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.).

Roko C. Buljan's user avatar

Prajeesh K P's user avatar

Try This

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,

note: The -webkit-scrollbar is not supported in Firefox or in Edge, prior version 79.

Abdulbasit's user avatar

Inside ::-webkit-scrollbar selected , the height represents the horizontal scrollbar and the width represents the vertical scrollbar. You can also use :horizontal psuedoclass.

    The Overflow Blog
Linked
Related
Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2022.10.3.39951

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *