Scroll-behavior

Свойства элемента ScrollBar

Свойство Описание
BackColor Цветовое оформление элемента управления.
Delay* Время между последовательными событиями при удержании кнопки.
ControlTipText Текст всплывающей подсказки при наведении курсора на полосу прокрутки.
Enabled Возможность взаимодействия пользователя с элементом управления. True – взаимодействие включено, False – отключено (цвет стрелок становится серым).
Height Высота элемента управления.
Left Расстояние от левого края внутренней границы пользовательской формы до левого края элемента управления.
Max Максимальное значение свойства Value.
Min Минимальное значение свойства Value.
Orientation** Задает горизонтальную или вертикальную ориентацию элемента управления ScrollBar.
SmallChange Шаг изменения значения свойства Value.
TabIndex Определяет позицию элемента управления в очереди на получение фокуса при табуляции, вызываемой нажатием клавиш «Tab», «Enter». Отсчет начинается с 0.
Top Расстояние от верхнего края внутренней границы пользовательской формы до верхнего края элемента управления.
Visible Видимость элемента ScrollBar. True – элемент отображается на пользовательской форме, False – скрыт.
Width Ширина элемента управления.

* По умолчанию свойство Delay равно 50 миллисекундам. Это означает, что первое событие (SpinUp, SpinDown, Change) происходит через 250 миллисекунд после нажатия кнопки, а каждое последующее событие – через каждые 50 миллисекунд (и так до отпускания кнопки).

** По умолчанию включена автоматическая ориентация, которая зависит от соотношения между шириной и высотой элемента управления. Если ширина больше высоты – ориентация горизонтальная, если высота больше ширины – ориентация вертикальная.

В таблице перечислены только основные, часто используемые свойства полосы прокрутки. Все доступные свойства отображены в окне Properties элемента управления ScrollBar.

Cross-browser Solution

For browsers that do not support the property, you could use JavaScript or a JavaScript library, like jQuery, to create a solution that will work for all browsers:

Example

<script src=»https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js»></script>
<script>$(document).ready(function(){  // Add smooth scrolling to all
links  $(«a»).on(‘click’, function(event) {    // Make sure this.hash
has a value before overriding default behavior    if (this.hash !== «») {
     
// Prevent default anchor click behavior      event.preventDefault();      //
Store hash      var hash = this.hash;      // Using jQuery’s animate() method
to add smooth page scroll      // The optional number (800) specifies the number
of milliseconds it takes to scroll to the specified area      $(‘html,
body’).animate({        scrollTop: $(hash).offset().top      }, 800, function(){        // Add hash (#) to URL when done scrolling (default click behavior)
       
window.location.hash = hash;      });    } // End if  });});</script>

Tip: Read more about the scroll-behavior property in our CSS Reference: CSS scroll-behavior Property.

❮ Previous
Next ❯

Настройка скроллбара с помощью Jquery

Если вам нравится программирование front-end, вы можете использовать Jquery-плагин JScrollPane. Он довольно прост в использовании. После того, как вы загрузили и подключили соответствующие файлы в заголовке документа, нужно вызвать одну Javascript-функцию для инициализации панели прокрутки. Вы можете легко изменить дизайн полосы прокрутки с помощью CSS или выбрать одну из существующих тем.

С помощью этого плагина вы можете создавать скроллинг для всех типов браузеров. Так что я бы посоветовал вам воспользоваться им, чтобы сэкономить время и охватить сразу все браузеры:

<link rel="stylesheet" type="text/css" href="jquery.jscrollpane.css" />

<!-- jQuery file from Google CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<!-- the jScrollPane script -->
<script src="jquery.jscrollpane.min.js"></script>

<script>
    $(document).ready(function () {
        $('.container').jScrollPane();
    }
});
</script>

Если вы захотите изменить настройки CSS scroll по умолчанию, предоставленные JScrollPane, нужно редактировать стили соответствующих элементов:

.jspTrack {
    background: #b46868;
    position: relative;
}

.jspDrag {
    background: #c43232;
    position: relative;
    cursor: pointer;
}

Images

SlideshowSlideshow GalleryModal ImagesLightboxResponsive Image GridImage GridTab GalleryImage Overlay FadeImage Overlay SlideImage Overlay ZoomImage Overlay TitleImage Overlay IconImage EffectsBlack and White ImageImage TextImage Text BlocksTransparent Image TextFull Page ImageForm on ImageHero ImageBlur Background ImageChange Bg on ScrollSide-by-Side ImagesRounded ImagesAvatar ImagesResponsive ImagesCenter ImagesThumbnailsBorder Around ImageMeet the TeamSticky ImageFlip an ImageShake an ImagePortfolio GalleryPortfolio with FilteringImage ZoomImage Magnifier GlassImage Comparison Slider

Использование псевдоэлементов CSS для настройки скроллбара

IE5.5 был первым браузером, поддерживающим основные стили для скроллинга. Используя свойство scrollbar-face-color, можно были изменить цвет полос прокрутки. Хотя это и не добавляло большого разнообразия, но все же лучше, чем стандартная полоса прокрутки в браузере. Поскольку это свойство по-прежнему поддерживается в Internet Explorer, его можно использовать для пользователей, предпочитающих этот браузер.

Для WebKit-браузерах в CSS существует множество вариантов стилизации: изменение цвета и ширины полосы прокрутки, ползунков. Элементы скроллинга можно выбрать с помощью следующих псевдоэлементов.

::webkit-scrollbar — позволяет настроить ширину и цвет полосы прокрутки. Когда этот псевдоэлемент указан, WebKit выключает свой встроенный рендеринг скроллбара и использует настройки, указанные для div scroll CSS

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

/* Для всех скроллбаров */
::-webkit-scrollbar {
    width: 8px;
    background-color: #F5F5F5;
}

/* Для определенных скроллбаров */
.mybox::-webkit-scrollbar {
    width: 12px;
    background-color: #434343;
}

::-webkit-scrollbar-thumb – Это ползунок скроллбара (чем вы держите и прокручиваете страницу). Он может иметь цвет или использовать градиент в качестве фона. Пример реализации:

::-webkit-scrollbar-thumb {
    width: 8px;
    background-image: -webkit-linear-gradient(#F5F5F5, #8A8A8A);
}

::-webkit-scrollbar-track – позволяет настроить трек скроллбара (путь движения ползунка). Синтаксис псевдоэлемента для CSS scroll:

::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
    border: 1px solid black;
    background-color: #F5F5F5;
}

::-webkit-scrollbar-button – разработчики CSS3 не упускают из виду маленькие кнопки на концах полосы прокрутки. Их также можно настроить, так как они помогают, когда страница длинная и скроллбар становится слишком маленьким для прокрутки. Это свойство стиля верхнего и нижнего углов (или левого и правого для горизонтальных полос прокрутки):

::-webkit-scrollbar-button {
    background-color: #7c2929;
}

::-webkit-scrollbar-corner – позволяет справиться с ситуацией, когда появляются обе полосы прокрутки и пересекаются в углу:

::-webkit-scrollbar-corner {
    background-color: #b3b3b3;
}

Вот несколько примеров, которые демонстрируют силу свойства scrolling CSS.

More

Fullscreen VideoModal BoxesDelete ModalTimelineScroll IndicatorProgress BarsSkill BarRange SlidersTooltipsDisplay Element HoverPopupsCollapsibleCalendarHTML IncludesTo Do ListLoadersStar RatingUser RatingOverlay EffectContact ChipsCardsFlip CardProfile CardProduct CardAlertsCalloutNotesLabelsCirclesStyle HRCouponList GroupList Without BulletsResponsive TextCutout TextGlowing TextFixed FooterSticky ElementEqual HeightClearfixResponsive FloatsSnackbarFullscreen WindowScroll DrawingSmooth ScrollGradient Bg ScrollSticky HeaderShrink Header on ScrollPricing TableParallaxAspect RatioResponsive IframesToggle Like/DislikeToggle Hide/ShowToggle Dark ModeToggle TextToggle ClassAdd ClassRemove ClassActive ClassTree ViewRemove PropertyOffline DetectionFind Hidden ElementRedirect WebpageZoom HoverFlip BoxCenter VerticallyCenter Button in DIVTransition on HoverArrowsShapesDownload LinkFull Height ElementBrowser WindowCustom ScrollbarHide ScrollbarShow/Force ScrollbarDevice LookContenteditable BorderPlaceholder ColorText Selection ColorBullet ColorVertical LineDividersAnimate IconsCountdown TimerTypewriterComing Soon PageChat MessagesPopup Chat WindowSplit ScreenTestimonialsSection CounterQuotes SlideshowClosable List ItemsTypical Device BreakpointsDraggable HTML ElementJS Media QueriesSyntax HighlighterJS AnimationsJS String LengthJS ExponentiationJS Default ParametersGet Current URLGet Current Screen SizeGet Iframe Elements

CSS Reference

CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Font FallbacksCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities

CSS Properties

align-content
align-items
align-self
all
animation
animation-delay
animation-direction
animation-duration
animation-fill-mode
animation-iteration-count
animation-name
animation-play-state
animation-timing-function

backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-repeat
background-size
border
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-style
border-bottom-width
border-collapse
border-color
border-image
border-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
border-left
border-left-color
border-left-style
border-left-width
border-radius
border-right
border-right-color
border-right-style
border-right-width
border-spacing
border-style
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-style
border-top-width
border-width
bottom
box-decoration-break
box-shadow
box-sizing
break-after
break-before
break-inside

caption-side
caret-color
@charset
clear
clip
clip-path
color
column-count
column-fill
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
column-span
column-width
columns
content
counter-increment
counter-reset
cursor

direction
display
empty-cells
filter
flex
flex-basis
flex-direction
flex-flow
flex-grow
flex-shrink
flex-wrap
float
font
@font-face
font-family
font-feature-settings
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-variant-caps
font-weight

gap
grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-gap
grid-column-start
grid-gap
grid-row
grid-row-end
grid-row-gap
grid-row-start
grid-template
grid-template-areas
grid-template-columns
grid-template-rows

hanging-punctuation
height
hyphens
@import
isolation
justify-content
@keyframes
left
letter-spacing

line-height
list-style
list-style-image
list-style-position
list-style-type

margin
margin-bottom
margin-left
margin-right
margin-top
max-height
max-width
@media
min-height
min-width
mix-blend-mode

object-fit
object-position
opacity
order
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-x
overflow-y

padding
padding-bottom
padding-left
padding-right
padding-top
page-break-after
page-break-before
page-break-inside
perspective
perspective-origin
pointer-events
position
quotes

resize
right
row-gap

scroll-behavior

tab-size
table-layout
text-align
text-align-last
text-decoration
text-decoration-color
text-decoration-line
text-decoration-style
text-indent
text-justify
text-overflow
text-shadow
text-transform
top

transform
transform-origin
transform-style
transition
transition-delay
transition-duration
transition-property
transition-timing-function

unicode-bidi
user-select

vertical-align
visibility

white-space
width
word-break
word-spacing
word-wrap
writing-mode

z-index

Use-cases

Use-case for color and/or width modification of scrollbars.

Dark colored webapp designs

Dark colored web app designs are particularly sensitive to the visual noise created from the intrusively high-contrast default platform scrollbars.

TweetDeck

Note that TweetDeck appears to only use three colors (but setting on multiple properties)

  • scrollbar-face-color: #e1e8ed;
  • scrollbar-track-color: #F5F8FA;
  • scrollbar-arrow-color: #292f33;

Webflow Designer

Sites blocking browsers

Some sites have designs that depend on scrollbar styling (specifically colors) so much that they block browsers that do not have such a feature:

https://webcompat.com/issues/8030

Google uses scrollbar width modification in Gmail and Google Docs portions, typically in narrower areas where a smaller scrollbar helps to show more content.

Subtler cleaner web app UI

Tab Atkins’s personal blog authoring web UI has a much narrower than default scrollbar to help reduce distraction and visual noise while writing a blog post.

Browser UI

Some browser(s) build UI using web platform features, sometimes adding internal only extensions. Ideally the a web platform features can be re-used, however if a new feature is needed for such UI, it does not mean it should also be added to features exposed to the web. Such internal-only extensions can be used as prototypes for experience.

Forcing Scrollbars

Scrollbars can appear in the usual place such as the browser window or on a tag. But you can also force scrollboxes onto other elements whenever their contents become too large to fit inside the box.

You can use CSS to create your own «inline scrollbars» by creating a box smaller than its contents. You can do this using the property. Specifically, you can use to force scrollbars to appear when the content overflows. This has an effect similar to inline frames (but using CSS is much simpler).

The above WebKit example on this page uses this technique. Here it is again but this time using inline styles and without all the scrollbar customization.

The property tells the browser what to do if the box’s contents is larger than the box itself. You can also specify , which will hide the scrollbars if the content doesn’t overflow, but display them if the content does overflow. You can also use to hide contents that don’t fit into the box and to automatically expand the box to fit the contents (this is the default setting)

Настройка направления и строгости привязки

Свойство scroll-snap-type задаётся контейнеру и позволяет указать направление, в котором происходит привязка прокрутки (x или y), а также строгость привязки (none, mandatory или proximity).

С направлением всё просто:

  • горизонтальная прокрутка — x или ключевое слово inline:
  • вертикальная прокрутка — y или ключевое слово block;
  • привязка в обоих направлениях — both.

Чуть сложнее увидеть разницу между значениями mandatory и proximity, которые определяют строгость привязки:

  • none — нет привязки к точке;
  • mandatory — обязательное смещение прокрутки к указанной точке;
  • proximity — смещение происходит только в тех ситуациях, когда область видимости находится близко к точке привязки. Степень близости браузер определяет самостоятельно.

Главный плюс mandatory — предсказуемость. Вы знаете, что браузер точно сместит область видимости к заданной точке. Главный минус — негибкость. Например, если содержимое при вертикальной прокрутке слишком большое по высоте, то пользователи окажутся в неприятной ситуации — они просто не смогут переместиться к определённому месту, браузер будет сразу перекидывать их к точке привязки.

See the Pen
Scroll Snap mandatory by Pochemuta (@pochemuta)
on CodePen.

Текст не помещается в области видимости по высоте, последние строчки невозможно прочитать, потому что срабатывает строгая привязка к прокрутке. Чтобы такого эффекта не было, можно заменить mandatory на proximity. Но и здесь остаётся опасность пролистывания — всё зависит от браузера. Проблему можно решить с помощью свойства scroll-padding, о котором мы поговорим ниже.

2

CSS Tutorial

CSS HOMECSS IntroductionCSS SyntaxCSS SelectorsCSS How ToCSS CommentsCSS Colors
Colors
RGB
HEX
HSL

CSS Backgrounds
Background Color
Background Image
Background Repeat
Background Attachment
Background Shorthand

CSS Borders
Borders
Border Width
Border Color
Border Sides
Border Shorthand
Rounded Borders

CSS Margins
Margins
Margin Collapse

CSS PaddingCSS Height/WidthCSS Box ModelCSS Outline
Outline
Outline Width
Outline Color
Outline Shorthand
Outline Offset

CSS Text
Text Color
Text Alignment
Text Decoration
Text Transformation
Text Spacing
Text Shadow

CSS Fonts
Font Family
Font Web Safe
Font Fallbacks
Font Style
Font Size
Font Google
Font Pairings
Font Shorthand

CSS IconsCSS LinksCSS ListsCSS Tables
Table Borders
Table Size
Table Alignment
Table Style
Table Responsive

CSS DisplayCSS Max-widthCSS PositionCSS OverflowCSS Float
Float
Clear
Float Examples

CSS Inline-blockCSS AlignCSS CombinatorsCSS Pseudo-classCSS Pseudo-elementCSS OpacityCSS Navigation Bar
Navbar
Vertical Navbar
Horizontal Navbar

CSS DropdownsCSS Image GalleryCSS Image SpritesCSS Attr SelectorsCSS FormsCSS CountersCSS Website LayoutCSS UnitsCSS SpecificityCSS !important

Images

SlideshowSlideshow GalleryModal ImagesLightboxResponsive Image GridImage GridTab GalleryImage Overlay FadeImage Overlay SlideImage Overlay ZoomImage Overlay TitleImage Overlay IconImage EffectsBlack and White ImageImage TextImage Text BlocksTransparent Image TextFull Page ImageForm on ImageHero ImageBlur Background ImageChange Bg on ScrollSide-by-Side ImagesRounded ImagesAvatar ImagesResponsive ImagesCenter ImagesThumbnailsBorder Around ImageMeet the TeamSticky ImageFlip an ImageShake an ImagePortfolio GalleryPortfolio with FilteringImage ZoomImage Magnifier GlassImage Comparison Slider

CSS Reference

CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Font FallbacksCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities

CSS Properties

align-content
align-items
align-self
all
animation
animation-delay
animation-direction
animation-duration
animation-fill-mode
animation-iteration-count
animation-name
animation-play-state
animation-timing-function

backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-repeat
background-size
border
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-style
border-bottom-width
border-collapse
border-color
border-image
border-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
border-left
border-left-color
border-left-style
border-left-width
border-radius
border-right
border-right-color
border-right-style
border-right-width
border-spacing
border-style
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-style
border-top-width
border-width
bottom
box-decoration-break
box-shadow
box-sizing
break-after
break-before
break-inside

caption-side
caret-color
@charset
clear
clip
clip-path
color
column-count
column-fill
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
column-span
column-width
columns
content
counter-increment
counter-reset
cursor

direction
display
empty-cells
filter
flex
flex-basis
flex-direction
flex-flow
flex-grow
flex-shrink
flex-wrap
float
font
@font-face
font-family
font-feature-settings
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-variant-caps
font-weight

gap
grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-gap
grid-column-start
grid-gap
grid-row
grid-row-end
grid-row-gap
grid-row-start
grid-template
grid-template-areas
grid-template-columns
grid-template-rows

hanging-punctuation
height
hyphens
@import
isolation
justify-content
@keyframes
left
letter-spacing

line-height
list-style
list-style-image
list-style-position
list-style-type

margin
margin-bottom
margin-left
margin-right
margin-top
max-height
max-width
@media
min-height
min-width
mix-blend-mode

object-fit
object-position
opacity
order
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-x
overflow-y

padding
padding-bottom
padding-left
padding-right
padding-top
page-break-after
page-break-before
page-break-inside
perspective
perspective-origin
pointer-events
position
quotes

resize
right
row-gap

scroll-behavior

tab-size
table-layout
text-align
text-align-last
text-decoration
text-decoration-color
text-decoration-line
text-decoration-style
text-indent
text-justify
text-overflow
text-shadow
text-transform
top

transform
transform-origin
transform-style
transition
transition-delay
transition-duration
transition-property
transition-timing-function

unicode-bidi
user-select

vertical-align
visibility

white-space
width
word-break
word-spacing
word-wrap
writing-mode

z-index

Свойства контейнера

Как и в случае с любым другим свойством, неплохо бы познакомиться со значениями, которые оно принимает. Свойства из спецификации «» применяются как к родителю, так и к дочерним элементам, с определёнными значениями для каждого. Подобно тому, как в Flexbox или CSS Grid родитель становится «flex-» или «grid-» контейнером, можно сказать, что здесь родитель становится scroll-контейнером.

Далее представлены свойства и значения для родительского контейнера и описание принципа их работы.

Значение «» определяет поведение, при котором всякий раз, когда пользователь прекращает прокрутку, браузер должен возвращать её к точке привязки.

Значение «» менее строгое – оно означает, что браузер может возвращаться к точке привязки, если ему это покажется уместным. Из моего опыта, если задано это значение, срабатывание происходит, если прокрутка остановилась в пределах нескольких сотен пикселей от точки привязки.

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

По умолчанию, при прокрутке дочерние элементы будут прижиматься к самым краям контейнера. Вы можете изменить это, задав для контейнера свойство . Оно имеет такой же синтаксис, что и свойство .

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

Что делать с дополнительным текстом?

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

  • Перепишите текст, чтобы он стал короче.
  • Позвольте, чтобы текст выходил за пределы контейнера, и надейтесь, что макет может растягиваться, чтобы справиться с этой ситуацией.
  • Обрежьте текст там, где он выходит за пределы контейнера.
  • Добавьте полосы прокрутки (для текста — обычно вертикальные), чтобы с их помощью можно было просмотреть весь текст.

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

HTML и CSS для этого:

<div style="overflow: auto; width:300px; height:200px;">здесь текст....</div>

overflow: auto; указывает браузеру добавлять полосы прокрутки (скролл), если текст выходит за границы блока div.

Но для того, чтобы это сработало, также нужно задать для этого блока div свойства ширины и высоты, чтобы определить границы контейнера.

Вы также можете обрезать текст, изменив значение свойства overflow с auto на hidden. Если вы не укажете свойство overflow, скролл на сайте работать не будет, и текст будет выходить за границы блока div.

Using Pseudo-Classes with Scrollbars

There are a number of pseudo-classes designed to work with scrollbars and give you much more accessibility when styling.

– applies to any scrollbar pieces that have a horizontal orientation.

– applies to any scrollbar pieces that have a vertical orientation.

– applies to buttons and track pieces. It indicates whether or not the button or track piece will decrement the view’s position when used (e.g., up on a vertical scrollbar, left on a horizontal scrollbar).

– applies to buttons and track pieces. It indicates whether or not a button or track piece will increment the view’s position when used (e.g., down on a vertical scrollbar, right on a horizontal scrollbar).

– applies to buttons and track pieces. It indicates whether the object is placed before the thumb.

– applies to buttons and track pieces. It indicates whether the object is placed after the thumb.

– applies to buttons and track pieces. It is used to detect whether a button is part of a pair of buttons that are together at the same end of a scrollbar. For track pieces it indicates whether the track piece abuts a pair of buttons.

– applies to buttons and track pieces. It is used to detect whether a button is by itself at the end of a scrollbar. For track pieces it indicates whether the track piece abuts a singleton button.

– applies to track pieces and indicates whether or not the track piece runs to the edge of the scrollbar, i.e., there is no button at that end of the track.

– applies to all scrollbar pieces and indicates whether or not a scrollbar corner is present.

– applies to all scrollbar pieces and indicates whether or not the window containing the scrollbar is currently active. (In recent nightlies, this pseudo-class now applies to ::selection as well. We plan to extend it to work with any content and to propose it as a new standard pseudo-class.)

Below, I’ve shown an example of some of the pseudo-classes being used to modify specific aspects of the scrollbar:

::-webkit-scrollbar:horizontal {
  background-color: lightgray;
}
::-webkit-scrollbar:vertical {
  background-color: #b6eff8;
}
::-webkit-scrollbar:hover {
  background-color: lightblue;
}

The few pseudo-classes used here would result in this view:

Using Pseudo Classes to Style the Scrollbar

Элементы скроллбара

Вы можете управлять отдельными элементами для кастомизации скроллбара:

  • webkit-scrollbar — Все поле скроллбара.
  • webkit-scrollbar-button — Кнопки скрола вверх и вниз (зачастую имеет иконки в виде стрелок).
  • webkit-scrollbar-track — Трек поля по которому передвигается ползунок скролла.
  • webkit-scrollbar-track-piece — Свободное место на треке (которое не занято ползунком).
  • webkit-scrollbar-thumb — Сам ползунок.
  • webkit-scrollbar-corner — Угол на скроллбаре, на котором как правило пересекаются вертикальный и горизонтальный скроллбар.
  • webkit-resizer — Если ваш скроллбар поддерживает изменение размера поля к которому он прикреплен, можете кастомизировать этот элемент.

#

CSS Properties

align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingbreak-afterbreak-beforebreak-insidecaption-sidecaret-color@charsetclearclipclip-pathcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-feature-settingsfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-variant-capsfont-weightgapgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerightrow-gapscroll-behaviortab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapwriting-modez-index

Некоторые мысли об удобстве для пользователей

Достоинством реализованного в CSS управления привязкой прокрутки является то, что вы не получаете прямой контроль над позицией прокрутки. Вместо этого, вы просто даёте браузеру список позиций для привязки таким образом, который соответствует платформе, способу ввода и пользовательским предпочтениям. Это значит, что поведение прокрутки, которое вы создаёте, на любой платформе будет ощущаться как нативное (то есть, с использованием тех же анимаций и т.д).

Считаю это ключевым преимуществом привязки прокрутки, реализованной с помощью CSS, перед JavaScript библиотеками, предлагающими схожую функциональность.

По моим личным ощущениям, это работает достаточно хорошо, особенно на мобильных устройствах. Возможно, из-за того, что «scroll snapping» уже является частью встроенного в мобильные платформы UI. Вспомните главный экран на iOS и Android устройствах – это, по сути, горизонтальный слайдер с точками привязки. Взаимодействие в Chrome на Android особенно приятно, потому что воспринимается как обычная прокрутка, но область видимости всегда останавливается на точке привязки:

Your browser does not support HTML5 video.

Для реализации такого поведения, определённо нужно проводить некоторые математические вычисления. Благодаря CSS Scroll Snapping мы добиваемся такого же результата без этого.

Конечно, мы не должны создавать точки привязки на всём подряд. Например, страницы со статьями прекрасно обойдутся и без них. Но я думаю, что они могут существенно улучшить удобство взаимодействия с приложение, если будут использованы в нужный момент – галереи изображений, слайдшоу кажутся хорошими кандидатами.

Итого

У элементов есть следующие геометрические свойства (метрики):

  • – ближайший CSS-позиционированный родитель или ближайший , , , .
  • – позиция в пикселях верхнего левого угла относительно .
  • – «внешняя» ширина/высота элемента, включая рамки.
  • – расстояние от верхнего левого внешнего угла до внутренного. Для операционных систем с ориентацией слева-направо эти свойства равны ширинам левой/верхней рамки. Если язык ОС таков, что ориентация справа налево, так что вертикальная полоса прокрутки находится не справа, а слева, то включает в своё значение её ширину.
  • – ширина/высота содержимого вместе с внутренними отступами , но без полосы прокрутки.
  • – ширины/высота содержимого, аналогично , но учитывают прокрученную, невидимую область элемента.
  • – ширина/высота прокрученной сверху части элемента, считается от верхнего левого угла.

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

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

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

Adblock
detector