Прокручиваемый html-блок

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

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 ❯

How To Create Custom Scrollbars

Chrome, Edge, Safari and Opera support the non-standard 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;}

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

Простой пример

В качестве простого примера демонстрации свойств мы будем использовать следующий элемент:

У элемента есть рамка (border), внутренний отступ (padding) и прокрутка. Полный набор характеристик

Обратите внимание, тут нет внешних отступов (margin), потому что они не являются частью элемента, для них нет особых JavaScript-свойств

Результат выглядит так:

Вы можете открыть этот пример в песочнице.

Внимание, полоса прокрутки

В иллюстрации выше намеренно продемонстрирован самый сложный и полный случай, когда у элемента есть ещё и полоса прокрутки. Некоторые браузеры (не все) отбирают место для неё, забирая его у области, отведённой для содержимого (помечена как «content width» выше).

Таким образом, без учёта полосы прокрутки ширина области содержимого (content width) будет , но если предположить, что ширина полосы прокрутки равна (её точное значение зависит от устройства и браузера), тогда остаётся только , и мы должны это учитывать. Вот почему примеры в этой главе даны с полосой прокрутки. Без неё некоторые вычисления будут проще.

Область (нижний внутренний отступ) может быть заполнена текстом

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

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

Style the Scrollbar

The process of styling includes styling the background track, setting the size border and color, and then the main scrollbar.

<!-- STYLE  SECTION -->
<style type="text/css">
/* Set the scrollbar width */
::-webkit-scrollbar {
    width: 16px;
}
 
/* Track */
::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); 
    -webkit-border-radius: 8px;
    border-radius: 8px;
}
 
/* Handle */
::-webkit-scrollbar-thumb {
    -webkit-border-radius: 8px;
    border-radius: 8px;
    background: #6be1a0;
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.5); 
}
::-webkit-scrollbar-thumb:window-inactive {
  background: rgba(255,0,0,0.4); 
}
</style>

Now we’d have a fully customized scrollbar, which would look like this in the browser:

A Customized Scrollbar

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.

Свойства элемента 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.

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

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

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

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

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

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

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

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

CSS Advanced

CSS Rounded CornersCSS Border ImagesCSS BackgroundsCSS ColorsCSS Color KeywordsCSS Gradients
Linear Gradients
Radial Gradients

CSS Shadows
Shadow Effects
Box Shadow

CSS Text EffectsCSS Web FontsCSS 2D TransformsCSS 3D TransformsCSS TransitionsCSS AnimationsCSS TooltipsCSS Style ImagesCSS Image ReflectionCSS object-fitCSS object-positionCSS ButtonsCSS PaginationCSS Multiple ColumnsCSS User InterfaceCSS Variables
The var() Function
Overriding Variables
Variables and JavaScript
Variables in Media Queries

CSS Box SizingCSS Media QueriesCSS MQ ExamplesCSS Flexbox
CSS Flexbox
CSS Flex Container
CSS Flex Items
CSS Flex Responsive

Create the Scrollbar

Creating a scrollbar is pretty easy. First, add two elements in HTML, a scrollbar wrapper (div) and a content wrapper (div):

<!-- HTML SECTION  -->
<div class="scrollbar">
    <div class="content">Lorem ipsum dolor sit amet</div>
</div>

In the style section, we’ll refer to the class to give scrollbar attributes and then to to set content size.

<!-- STYLE  SECTION -->
<style type="text/css">
.scrollbar{
  width: 300px;
  height: 200px;
  background-color:lightgray;
  margin-top:40px;
  margin-left:40px;
  overflow: scroll; /*if the content extends beyond width and height use the scrollbar*/
  float:left;
}
.content{
  height:450px;
  width: 500px;
} 
</style>

Simple as that, we have create a scrollable div inside a page that looks like this for now:

A Basic Scrollbar

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

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.

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

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

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

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

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

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

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

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

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

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

overflow-x and overflow-y

The and properties specifies
whether to change the overflow of content just horizontally or vertically (or
both):

specifies what to do with the left/right edges of the
content. specifies what to do with the top/bottom edges of the
content.

You can use the overflow property when you want to have better control of the layout. The overflow property specifies what happens if content overflows an element’s box.

Example

div {  overflow-x: hidden; /* Hide horizontal scrollbar
*/  overflow-y: scroll; /* Add vertical scrollbar */}

All CSS Overflow Properties

Property Description
overflow Specifies what happens if content overflows an element’s box
overflow-x Specifies what to do with the left/right edges of the content if it overflows the element’s content area
overflow-y Specifies what to do with the top/bottom edges of the content if it overflows the element’s content area

❮ Previous
Next ❯

CSS Overflow

The property specifies whether to clip
the content or
to add scrollbars when the content of an element is too big to fit in the specified
area.

The property has the following values:

  • — Default. The overflow is not clipped.
    The content renders outside the element’s box
  • — The overflow is clipped, and the rest of the content will be invisible
  • — The overflow is clipped, and a scrollbar is added to see the rest of the content
  • — Similar to ,
    but it adds scrollbars only when necessary

Note: The property only works for block elements with a specified height.

Note: In OS X Lion (on Mac), scrollbars are hidden by default and only shown when being used (even though «overflow:scroll» is set).

Why not pseudos

Why not pseudo-elements?

Scrollbars are more like text-decoration, borders, outlines than they are things like ::before/::after, or ::first-letter or ::first-line.

Just as we don’t have separate pseudo-elements for ::text-underline ::text-overline ::text-strike-through, or different border or outline sides, it doesn’t make sense to have separate pseudos for scrollbars or scrollbar parts!

, a feature mistakenly exposed to the web, should not need to be implemented everywhere for interop.

The scrollbar pseudo-elements as a set are not a good idea:

  • OSs continuously evolve their scrollbar designs to provide better user experience, beyond the ability of any set of pseudo-elements to accurately model this over time.
  • MacOS and Ubuntu, both have quite different scrollbar structure than that on Windows. Having something like the scrollbar pseudo-elements specified may make it harder for browsers to have decent behavior on different platforms.
  • Different OSs having different scrollbar structure also means testing interop is harder, because you would need to take not only engines but also platforms into account.

Menus

Icon BarMenu IconAccordionTabsVertical TabsTab HeadersFull Page TabsHover TabsTop NavigationResponsive TopnavNavbar with IconsSearch MenuSearch BarFixed SidebarSide NavigationResponsive SidebarFullscreen NavigationOff-Canvas MenuHover Sidenav ButtonsSidebar with IconsHorizontal Scroll MenuVertical MenuBottom NavigationResponsive Bottom NavBottom Border Nav LinksRight Aligned Menu LinksCentered Menu LinkEqual Width Menu LinksFixed MenuSlide Down Bar on ScrollHide Navbar on ScrollShrink Navbar on ScrollSticky NavbarNavbar on ImageHover DropdownsClick DropdownsCascading DropdownDropdown in TopnavDropdown in SidenavResp Navbar DropdownSubnavigation MenuDropupMega MenuMobile MenuCurtain MenuCollapsed SidebarCollapsed SidepanelPaginationBreadcrumbsButton GroupVertical Button GroupSticky Social BarPill NavigationResponsive Header

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

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

Adblock
detector