Свойства CSS overflow (hidden, visible, auto, scroll) и его разновидности для отображения контента блочных элементов. Создание div с вертикальной прокруткой с использованием CSS


3. Принудительная установка вертикальной и горизонтальной прокрутки в блоке CSS
4. Пример div блока с прокруткой

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

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

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

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

Код CSS

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

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

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

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

Код CSS

Prokrutka {
width:150px; /* ширина нашего блока */
height:100px; /* высота нашего блока */


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

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

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

Код HTML и CSS

Prokrutka {
height:150px; /* высота нашего блока */
background: #fff; /* цвет фона, белый */
border: 1px solid #C1C1C1; /* размер и цвет границы блока */


}

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

Код HTML и CSS



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



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



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

The web is a rather vertical place. You read a web site like you read a physical page: left to right, top to bottom. But sometimes, you want to step away from the verticality of it all and do something crazy: make a horizontal list. Or even crazier, a horizontal site!

I’d be nice if we could do something like this:

/* This isn"t real */ div { scroll-direction: horizontal; }

Unfortunately, that’s not going to happen. It’s not even on the roadmap for CSS.

That"s too bad, as at the company I work for this would be quite useful. We do quite a few web presentations. Presentations are a very horizontal thing - usually slides have a 4:3 or 16:9 radius. This means we always have a struggle between the horizontality of presentations and the verticality of web technologies. And by we, I mean me. But if there’s one thing I like, it’s a challenge.

Another Use Case

The specific use case that led to me digging into this idea that a customer wanted to show all their products on a single slide. Of course, their product catalog was way too big to put in a single view. So we decided to split them up into three categories, each horizontally scrollable. So the three most prominent product in each category were visible and less important products were still easily accessible.

A Non-JavaScript Way

There are, no surprise, numerous ways to do this in JavaScript. Some of them are .

I was curious if it was possible to do in pure CSS. The solution ended up being fairly straightforward:

  • Create a container with items
  • Rotate the container 90 degrees counterclockwise so the bottom is to the right
  • Rotate the items back to correct-side up

Step 1) Set up the container

Make a

, and make a bunch of child elements.

In this example, our side-scrolling container will be 300px wide, with 8 items of 100×100px each. These are arbitrary sizes; they could be anything.

item 1
item 2
item 3
item 4
item 5
item 6
item 7
item 8

The height of the container will become the "width" and vice-versa. So below, the "width" of our container will be 300px:

Horizontal-scroll-wrapper { width: 100px; height: 300px; overflow-y: auto; overflow-x: hidden; }

Now the children:

Horizontal-scroll-wrapper > div { width: 100px; height: 100px; }

Step 2) Rotating the container

Now we rotate the container -90 degrees with a CSS transform . And there you have it: a horizontal scroller.

Horizontal-scroll-wrapper { ... transform: rotate(-90deg); transform-origin: right top; }

There’s just one tiny issue: our children have rotated too, and now anything within is on its side.

Step 3) Rotate the children back upright

How would we go about getting the children upright again? Rotate them back using another, opposite CSS transform .

Horizontal-scroll-wrapper > div { ... transform: rotate(90deg); transform-origin: right top; }

Step 4) Fixing the positioning

It’s starting to look alright, but there are still some issues.

By rotating the wrapper using the top right as an anchor point, our left side has shifted by the width of the container. If you find this difficult to understand, just put your finger on the top right corner of a page and rotate it. The solution: shift it back with translateY .

Better. But the first item is still missing, due to the same phenomenon happening to the items. We could fix this by giving the first child a top margin of its width or by translating all items the same way we did the wrapper. The easiest way I’ve found though is to add a top padding to the wrapper equal to the item width, creating a kind of buffer for the items.

Horizontal-scroll-wrapper { ... transform:rotate(-90deg) translateY(-100px); ... }

Demo

Here"s another where you can see non-square children:

Compatibility

I have tested on the devices immediately available to me.

Device OS Browser works?
Desktop Win10 Chrome 54 Y
Desktop Win10 Firefox 47 Y (w scrollbars)
Desktop Win10 IE11 Y (w scrollbars)
Desktop Win10 Opera 41 Y
Desktop Win10 Vivaldi 1.4 Y
Laptop (touch screen) Win10 Chrome 54 N
Samsung Galaxy S3 Android 4.3 Chrome Mobile 52 Y
Samsung Galaxy S6 Android 5.0 Chrome Mobile 52 Y
Nexus 6P Android 6 Chrome Mobile 52 Y
iPad2 iOS Chrome Mobile 52 N
iPad2 iOS Safari Mobile 9.0 N
iPad Air 2 iOS Safari Mobile 9.0 N

Desktop

Since the styling of scrollbars is currently only supported by WebKit/Blink, Firefox and IE still show the ugly gray ones. You could sniff this out with JavaScript and hide them completely, but that’s stuff for another tutorial.

Using the mouse scroll wheel works great on desktops. My laptop was a different matter, though. Both the touchscreen and the touchpad acted as though the div was not rotated.

Mobile

I was kind of surprised to find that Android actually understood that the container had been rotated, and let you scroll sideways by swiping left and right.

iOS on the other hand did not play nice. It acted like the container did not get rotated, so you have to swipe up and down to scroll sideways, which of course is counterintuitive. Also, swiping left and right moves the items up and down in their wrapper, which is unexpected and weird. Setting the overflow to hidden does not alleviate this issue.

Conclusion

According to Can I Use, CSS transforms are currently supported by over 93% of users (at the time of this writing, November 2016), so there’s no issue there.

Beware of using this in production, though. I have tested this on some devices, but not at all extensively or in depth.

The greatest issue is with touch inputs that requiring you to swipe up and down to go left and right. A possible solution would be to include a message on your site explaining this, but you’d have to rely on people actually reading your message. And even then it’d still be counterintuitive. Another possible solution would be to capture the touch input with JavaScript on those devices, but then you’d be better off just doing the whole thing in JavaScript and foregoing this CSS hack completely.

Иногда необходимо большой кусок текста разместить в маленьком окошке, который полностью туда не помещается, для решения этой проблемы легко создать слой с прокруткой — div с прокруткой .

Понадобится

Слой с фиксированным размером и CSS-стиль.

CSS

В CSS-классе.scroll устанавливаются параметры 600px в длину и 300px в высоту, внутренний отступ, рамка и цвет фона. НО! Самое главное параметр overflow:auto устанавливает появление полосы прокрутки при количестве текста большим, чем размер слоя.

Scroll { width:500px; height:300px; /* необходим фиксированный размер */ overflow:auto; /* прокрутка появляется по необходимости */ padding:10px 20px; border:#999 1px solid; background-color:#FAFAFA; }

HTML

Наибольшее распространение получили этиленгликолевые охлаждающие жидкости на основе этиленгликоля и воды (дистиллированной) с комплексом присадок. Антифризы получаются как водные растворы соответствующих концентратов. В процессе эксплуатации качество антифриза можно контролировать по плотности. Из охлаждающей жидкости в процессе эксплуатации в первую очередь испаряется вода, которую следует периодически доливать (дистиллированную). Необходимо следить за тем, чтобы в антифризы не попадали бензин и масла, так как они вызывают вспенивание и выброс жидкости из системы. Срок службы охлаждающих жидкостей типа «Тосол» и «Лена» ограничивается долговечностью присадок и обычно составляет 2 года; по пробегу для различных автомобилей в среднем составляет 50000 км. При первом техобслуживании подержанного автомобиля следует заменить охлаждающую жидкость. После слива старой жидкости заправьте систему чистой водой, пустите двигатель и дайте ему поработать на холостых оборотах 15-20 минут; затем слейте воду и заправьте систему новой охлаждающей жидкостью.

Результат

На экране вы увидите небольшую рамку с текстом и с границей серого цвета.

Наибольшее распространение получили этиленгликолевые охлаждающие жидкости на основе этиленгликоля и воды (дистиллированной) с комплексом присадок.

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

Срок службы охлаждающих жидкостей типа «Тосол» и «Лена» ограничивается долговечностью присадок и обычно составляет 2 года; по пробегу для различных автомобилей в среднем составляет 50000 км.

При первом техобслуживании подержанного автомобиля следует заменить охлаждающую жидкость. После слива старой жидкости заправьте систему чистой водой, пустите двигатель и дайте ему поработать на холостых оборотах 15-20 минут; затем слейте воду и заправьте систему новой охлаждающей жидкостью.