overflow

CSS overflow Property

The overflow property specifies what should happen if content overflows an element’s box.

This property specifies whether to clip content or to add scrollbars when an element’s content is too big to fit in a specified area.

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

Default value: visible
Inherited: no
Animatable: no. Read about animatable
Version: CSS2
JavaScript syntax: object.style.overflow=»scroll» Try it

Browser Support

The numbers in the table specify the first browser version that fully supports the property.

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

CSS Syntax

Property Values

Value Description Demo
visible The overflow is not clipped. It renders outside the element’s box. This is default Demo ❯
hidden The overflow is clipped, and the rest of the content will be invisible. Content can be scrolled programmatically (e.g. by setting scrollLeft or scrollTo()) Demo ❯
clip The overflow is clipped, and the rest of the content will be invisible. Forbids scrolling, including programmatic scrolling. Demo ❯
scroll The overflow is clipped, but a scroll-bar is added to see the rest of the content Demo ❯
auto If overflow is clipped, a scroll-bar should be added to see the rest of the content Demo ❯
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

Источник

overflow

Обрезать ли то, что не поместилось в блок? Или показывать скролл?

Время чтения: меньше 5 мин

Кратко

Скопировать ссылку «Кратко» Скопировано

Свойство overflow позволяет буквально определить, что делать с содержимым блочного (то есть для элемента, у которого display определяется как block , inline — block , flex или grid ) элемента, если оно не влезает в размеры — отобразить или обрезать (с полосами прокрутки или без).

Пример

Скопировать ссылку «Пример» Скопировано

Если содержимое блока будет больше, чем границы блока, оно будет «обрезано»:

 .article  /* Задаём ограничения по размеру блока */ width: 300px; height: 300px; overflow: hidden;> .article  /* Задаём ограничения по размеру блока */ width: 300px; height: 300px; overflow: hidden; >      

Как пишется

Скопировать ссылку «Как пишется» Скопировано

 .selector  overflow: hidden;> .selector  overflow: hidden; >      

Как понять

Скопировать ссылку «Как понять» Скопировано

Синтаксис свойства позволяет задать два значения — для оси x и оси y. Если указано одно значение, оно равнозначно применяется для обеих осей. Аналогичного результата можно добиться, используя самостоятельные CSS-свойства overflow — x и overflow — y .

Значения

Скопировать ссылку «Значения» Скопировано

  • visible — содержимое отображается снаружи родительского блока, если его размеры больше размеров «родительского» блока (значение по умолчанию);
  • hidden — содержимое, выходящее за пределы «родительского» блока, обрезается по его границам без прокрутки;
  • clip — новое значение, похожее по результату на hidden , но границы родительского блока рассчитываются с учётом внутренних отступов;
  • scroll — контент обрезается по границам «родительского» блока, но внутри этой области содержимое доступно с помощью прокрутки;
  • auto — если содержимое переполняет блок, контент будет доступен для прокрутки.

Подсказки

Скопировать ссылку «Подсказки» Скопировано

💡 Чтобы контент внутри блока можно было скроллить, его содержимое должно явно превышать высоту родительского блока. Этого можно добиться или явно задав ему height , или ограничив высоту родительского блока.

💡 Задавая родительскому блоку фиксированную высоту, учитывайте, что, если не указан box — sizing : border — box , то это значение не учитывает внутренние отступы, заданные с помощью padding , что может спровоцировать появление нежелательной прокрутки.

На практике

Скопировать ссылку «На практике» Скопировано

Realetive советует

Скопировать ссылку «Realetive советует» Скопировано

🛠 При вёрстке «классических» макетов необходимости в управлении полосой прокрутки практически нет. Чтобы избежать появления нежелательных полос прокрутки, минимизируйте явное задание высоты (кроме случаев, где это действительно необходимо).

Ещё один пример, когда будет полезно знание свойства overflow — обрезание текста с многоточием (в сочетании со свойством text — overflow : ellipsis или недокументированного -webkit — line — clamp ):

Источник

CSS Layout — Overflow

The CSS overflow property controls what happens to content that is too big to fit into an area.

This text is really long and the height of its container is only 100 pixels. Therefore, a scrollbar is added to help the reader to scroll the content. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem.

CSS Overflow

The overflow 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 overflow property has the following values:

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

Note: The overflow 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).

overflow: visible

By default, the overflow is visible , meaning that it is not clipped and it renders outside the element’s box:

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

overflow: hidden

With the hidden value, the overflow is clipped, and the rest of the content is hidden:

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

overflow: scroll

Setting the value to scroll , the overflow is clipped and a scrollbar is added to scroll inside the box. Note that this will add a scrollbar both horizontally and vertically (even if you do not need it):

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

overflow: auto

The auto value is similar to scroll , but it adds scrollbars only when necessary:

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

overflow-x and overflow-y

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

overflow-x specifies what to do with the left/right edges of the content.
overflow-y 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-wrap Specifies whether or not the browser can break lines with long words, if they overflow its container
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

Источник

overflow

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

Синтаксис

overflow: auto | hidden | scroll | visible | inherit

Значения

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

HTML5 CSS2.1 IE Cr Op Sa Fx

       
Duis te feugifacilisi

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Результат данного примера показан на рис. 1.

Применение свойства overflow

Рис. 1. Применение свойства overflow

Объектная модель

[window.]document.getElementById(» elementID «).style.overflow

Браузеры

Internet Explorer до версии 7.0 включительно:

  • не поддерживает значение inherit ;
  • относительно позиционированные дочерние элементы, значения overflow у которых заданы как auto или scroll ведут себя словно у них задано position : fixed .
  • Сочетание overflow со значением scroll со свойствами max-height и float может привести к пропаданию элементов веб-страницы, в браузере выводится пустой экран.
  • Для блока, у которого указаны свойства float и overflow со значением scroll , игнорируется ширина, заданная через свойство max-width .
  • Высота блока с горизонтальной полосой прокрутки увеличивается на высоту скролбара, хотя по спецификации CSS заданные размеры должны включать в себя и полосы прокрутки.

Источник

Читайте также:  Java 11 docker alpine
Оцените статью