Пример работы CSS

overflow-y¶

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

Демо¶

Синтаксис¶

 1 2 3 4 5 6 7 8 9 10 11 12 13
/* Keyword values */ overflow-y: visible; overflow-y: hidden; overflow-y: clip; overflow-y: scroll; overflow-y: auto; /* Global values */ overflow-y: inherit; overflow-y: initial; overflow-y: revert; overflow-y: revert-layer; overflow-y: unset; 

Значения¶

visible Отображается всё содержание элемента, даже за пределами установленной высоты. hidden Отображается только область внутри элемента, остальное будет скрыто. scroll Всегда добавляется вертикальная полоса прокрутки. auto Вертикальная полоса прокрутки добавляется только при необходимости.

Значение по-умолчанию: visible

Применяется к блочным элементам

Спецификации¶

Описание и примеры¶

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 html> head> meta charset="utf-8" /> title>overflow-ytitle> style> body  overflow-y: hidden; /* Убираем вертикальную полосу прокрутки */ > .layer  width: 300px; /* Ширина блока */ height: 150px; /* Высота блока */ padding: 5px; /* Поля вокруг текста */ > style> head> body> div class="layer"> h2>Гетерогенный голубой гельh2> p> Кондуктометрия мягко передает электронный способ получения независимо от последствий проникновения метилкарбиола внутрь. p> div> body> html> 

Источник

How to Make a Div Vertically Scrollable

CSS allows us to make a vertically scrollable. It can be easily done by using the overflow property. The overflow property has different values. E.g., overflow: auto; and an axis hiding procedure like overflow-x: hidden; and overflow-y: auto; will make a bar scrollable vertically and horizontally, and the «auto» value will add only a vertically scrollable bar.

For a scrollable bar, use the x and y-axis. Set the overflow-x: hidden; and overflow-y: auto; to automatically hide the horizontal scrollbar and show a vertical scrollbar.

Let’s see an example, where the is vertically scrollable.

Create HTML

body> h2>W3docsh2> div Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when a n unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. div> body>

Add CSS

  • Set the background-color, width, and height properties for the element.
  • Use the overflow-x property to specify whether the content must be hidden, visible or scrolling horizontally when the content overflows the element’s left and right edges. Set the «hidden» value.
  • Use the overflow-y property to specify whether the content must be hidden, visible or scrolling vertically when the content overflows the element’s top and bottom edges. Set the «auto» value.
  • Use the text-align property with its «center» value.
div.scroll < background-color: #fed9ff; width: 600px; height: 150px; overflow-x: hidden; overflow-y: auto; text-align: center; padding: 20px; >

Let’s bring the parts together and see the whole code!

Example of making a vertically scrollable using the overflow-x and overflow-y properties:

html> html> head> title>Title of the document title> style> div.scroll < background-color: #fed9ff; width: 600px; height: 150px; overflow-x: hidden; overflow-y: auto; text-align: center; padding: 20px; > style> head> body> h2>W3docs h2> div class="scroll"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. div> body> html>

Result

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using ‘Content here, content here’, making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for ‘lorem ipsum’ will uncover many web sites still in their infancy.

Example of making a vertically scrollable using the overflow property:

html> html> head> title>Title of the document title> style> div.scroll < background-color: #fed9ff; width: 600px; height: 150px; overflow: auto; text-align: justify; padding: 20px; > style> head> body> h2>W3docs h2> div class="scroll"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. div> body> html>

Источник

Как создать div блок с прокруткой?

1. Что такое overflow в CSS?
2. Свойства и значения overflow
3. Принудительная установка вертикальной и горизонтальной прокрутки в блоке CSS
4. Пример div блока с прокруткой

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

О полезном свойстве overflow

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

overflow-x — отвечает за отображением содержания блочного элемента по горизонтали.
overflow-y — отвечает за отображением содержания блочного элемента по вертикали.

.prokrutka overflow: auto; /* свойство для прокрутки по горизонтали. Автоматом, если содержимое больше блока */ 
>

Свойства и значения overflow

visible — отображается все содержание элемента, даже за пределами установленной ширины.
hidden — отображается только область внутри элемента, остальное скрыто.
scroll — принудительно добавляется горизонтальная (y) или горизонтальная (x) полоса прокрутки.
auto — автоматом добавляется горизонтальная полоса прокрутки, в случае если блок меньше.

Рассмотри пример класса CSS. В width и height устанавливаем нужные нам ширину и высоту блока (за них не будет выходить содержимое блока), а свойством overflow: auto; задаем прокрутку по горизонтали в случае надобности

.prokrutka width:150px; /* ширина нашего блока */ 
height:100px; /* высота нашего блока */
background: #fff; /* цвет фона, белый */
border: 1px solid #C1C1C1; /* размер и цвет границы блока */
overflow: auto; /* свойство для прокрутки по горизонтали. Автоматом, если больше блока */
>

Принудительная установка прокрутки в блоке CSS

Можно также принудительно создать прокрутку по высоте и ширине. Для этого каждой оси: overflow-y: scroll; (вертикаль) overflow-x: scroll; (горизонталь) укажем параметр scroll, принудительная прокрутка.

Код HTML и CSS

.prokrutka height:150px; /* высота нашего блока */ 
background: #fff; /* цвет фона, белый */
border: 1px solid #C1C1C1; /* размер и цвет границы блока */
overflow-x: scroll; /* прокрутка по горизонтали */
overflow-y: scroll; /* прокрутка по вертикали */
>

Пример div блока с прокруткой

Код HTML и CSS

 









А тут много-много разного текста и прочей информации. А тут много-много разного текста и прочей информации. А тут много-много разного текста и прочей информации. А тут много-много разного текста и прочей информации. А тут много-много разного текста и прочей информации. А тут много-много разного текста и прочей информации. А тут много-много разного текста и прочей информации. А тут много-много разного текста и прочей информации.


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

Демонстрация Скачать исходники
Можно указать принудительную прокрутку только для одной оси. Для этого соответственно уберите строку либо с overflow-x, либо с overflow-y.

Спасибо за внимание! Надеюсь статья была полезна!

Источник

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

Сегодня будем стилизовать скролл с помощью 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 свойства.

/* полоса прокрутки (скроллбар) */ ::-webkit-scrollbar < width: 24px; /* ширина для вертикального скролла */ height: 8px; /* высота для горизонтального скролла */ background-color: #143861; >/* ползунок скроллбара */ ::-webkit-scrollbar-thumb < background-color: #843465; border-radius: 9em; box-shadow: inset 1px 1px 10px #f3faf7; >::-webkit-scrollbar-thumb:hover < background-color: #253861; >/* Стрелки */ ::-webkit-scrollbar-button:vertical:start:decrement < background: linear-gradient(120deg, #02141a 40%, rgba(0, 0, 0, 0) 41%), linear-gradient(240deg, #02141a 40%, rgba(0, 0, 0, 0) 41%), linear-gradient(0deg, #02141a 30%, rgba(0, 0, 0, 0) 31%); background-color: #f6f8f4; >::-webkit-scrollbar-button:vertical:end:increment < background: linear-gradient(300deg, #02141a 40%, rgba(0, 0, 0, 0) 41%), linear-gradient(60deg, #02141a 40%, rgba(0, 0, 0, 0) 41%), linear-gradient(180deg, #02141a 30%, rgba(0, 0, 0, 0) 31%); background-color: #f6f8f4; >::-webkit-scrollbar-button:horizontal:start:decrement < background: linear-gradient(30deg, #02141a 40%, rgba(0, 0, 0, 0) 41%), linear-gradient(150deg, #02141a 40%, rgba(0, 0, 0, 0) 41%), linear-gradient(270deg, #02141a 30%, rgba(0, 0, 0, 0) 31%); background-color: #f6f8f4; >::-webkit-scrollbar-button:horizontal:end:increment

mCustomScrollbar

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

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

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

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

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

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

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

Источник

Читайте также:  Макет device html academy
Оцените статью