display

CSS display Property

The display property defines the type of the box which is used for an HTML element.

With the display property we can override the initial value of an element. For example, a block-level element could be displayed as an inline element by specifying a value of «inline». An inline element does not accept the height and width properties. It will just ignore it.

In HTML, the default values of the display property are taken from the behaviors which are described in the HTML specifications or from the browser or user default stylesheet. On the other hand, the default value in XML is «inline».

There are several main box formats in CSS:

  • Inline
    Inline elements or inline-level elements are boxes flowing in a line without breaking it. The , , elements are part of a line box but cannot cause a line break. Inline elements can have padding and margins, but they cannot have width and height because defining them on an inline won’t change its dimensions. Specifying padding and margins on the element will push the other elements on the line only horizontally. However, an inline-level element can accept width and height, if it is set to be an inline-block element using the display property.
  • Inline-block
    Inline-block elements are the same as inline element except that they except width and height. The width and height push the elements on the line both horizontally and vertically.
  • Block
    Block boxed or block-level elements do not sit in a line box but break past it. By default, they occupy as much horizontal space as possible. Block-level elements can contain other block-level elements. The , , — , , , and are examples of block level elements.
  • Flex
    The display property is also used for Flexbox. The flex value generates a block-level box for the element and lays out the content according to the Flexbox model. Here you can read about The Ultimate Guide to Flexbox.
  • Grid
    The display property initially sets the Grid layout. It generates a block-level box for the element laying out the content according to the Grid model.
  • Table Values
    Display values allows you to make non-table elements behave like table elements. Each of the table values forces the element to behave like a corresponding table element in HTML. The inline-table behaves like a HTML element, but as an inline box. There is a block-level context inside the table box.

Syntax

display: inline | block | contents | flex | grid | inline-block | inline-flex | inline-grid | inline-table | list-item | run-in | table | table-caption | table-column-group | table-header-group | table-footer-group | table-row-group | table-cell | table-column | table-row | none | initial | inherit;

Example of the display property:

html> html> head> title>Title of the document title> style> .display li < display: inline; margin-right: 10px; > style> head> body> h2>Display property example h2> p>Here the list item is with its initial value: p> ul> li>List iteam li> li>List iteam li> ul> p>Here the list item is used with the display property. The "inline" value is used: p> ul class="display"> li>List iteam 1 li> li>List iteam 2 li> ul> body> html>

Result

CSS display Property

Example of the display property with the «inline» and «block» values:

html> html> head> title>Title of the document title> style> .inline < border: 1px solid #1c87c9; display: inline; > .block < border: 1px solid #1c87c9; display: block; height: 30px; width: 300px; > style> head> body> h2>Display property example h2> p>Here the list item is with "initial" value. We see that the "inline" value does not accept height and width: p> span>This is some text. span> span class="inline">This is another text. span> hr> p>Here the list item is used with the "block" value of the display property: p> span class="block">This is some text. span> span class="block">This is another text. span> body> html>

Example of the display property with the «block» value:

html> html> head> title>The title of the document title> style> .block < display: block; border: 1px solid #666; background-color: #eee; padding: 10px; width: 200px; > .hello < border: 1px solid #1c87c9; background-color: #8ebf42; padding: 10px; > style> head> body> h2>Display property example h2> div class="block"> Lorem Ipsum is 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. div class="hello">HELLO! div> It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. div> body> html>

Example of the display property with the «contents» value:

html> html> head> title>Title of the document title> style> .contents < display: contents; border: 1px solid #666; background-color: #eee; padding: 10px; width: 200px; > .hello < border: 1px solid #1c87c9; background-color: #ccc; padding: 10px; text-align: center; > style> head> body> h2>Display property example h2> div class="contents"> Lorem Ipsum is 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. div class="hello">HELLO! div> It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. div> body> html>

Example of the display property with the «flex» value:

html> html> head> title>Title of the document title> style> #flex < width: 300px; height: 100px; border: 1px solid #c3c3c3; display: -webkit-flex; /* Safari */ -webkit-justify-content: center; /* Safari 6.1+ */ display: flex; justify-content: center; > div < width: 70px; height: 70px; > style> head> body> h2>Display property example h2> p>Here the "display: flex;" is used: p> div id="flex"> div style="background-color: #1c87c9;">1 div> div style="background-color: #666;">2 div> div style="background-color: #8ebf42;">3 div> div> body> html>

Values

Value Description Play it
inline Represents an element as an inline element. Play it »
block Represents an element as a block element. Play it »
contents The container disappears, thus making the child elements children of the element the next level up in the DOM. Play it »
flex Represents an element as a block-level-flex container. Play it »
grid Represents an element as a block-level grid container. Play it »
inline-block Represents an element as an inline-level block container. Play it »
inline-flex Represents an element as an inline-level flex container. Play it »
inline-grid Represents an element as an inline-level grid container. Play it »
inline-table Represents an element as an inline-level table. It behaves like an HTML element, but as an inline box, and not as a block-level box. Inside the table box is a block-level context. Play it »
list-item The element behaves like HTML element. Play it »
run-in Represents an element as block or inline according to context. Play it »
table The element behaves like HTML element. Play it »
table-caption The element behaves like HTML element. Play it »
table-column-group The element behaves like HTML element. Play it »
table-header-group The element behaves like HTML element. Play it »
table-footer-group The element behaves like HTML element. Play it »
table-row-group The element behaves like HTML element. Play it »
table-cell The element behaves like HTML element. Play it »
table-column The element behaves like HTML element. Play it »
table-row The element behaves like HTML element. Play it »
none Means that the element won’t be shown at all. Play it »
initial Makes the property use its default value. Play it »
inherit Inherits the property from its parent element.
Читайте также:  Python reply keyboard markup

Browser support

Источник

display

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

Синтаксис

display: block | inline | inline-block | inline-table | list-item | none | run-in | table | table-caption | table-cell | table-column-group | table-column | table-footer-group | table-header-group | table-row | table-row-group

Значения

Список возможных значений этого свойства, понимаемый разными браузерами очень короткий — block , inline , list-item и none . Все остальные допустимые значения поддерживаются браузерами выборочно. В табл. 1 приведены некоторые популярные браузеры и их поддержка различных значений.

Табл. 1. Поддержка браузерами значений display

Значение Описание IE6 IE7 IE8 Cr2 Cr8 Op9.2 Op10 Sa3.1 Sa5 Fx3 Fx4
block Элемент показывается как блочный. Применение этого значения для встроенных элементов, например тега , заставляет его вести подобно блокам — происходит перенос строк в начале и в конце содержимого.
inline Элемент отображается как встроенный. Использование блочных тегов, таких как и

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

inline-block Это значение генерирует блочный элемент, который обтекается другими элементами веб-страницы подобно встроенному элементу. Фактически такой элемент по своему действию похож на встраиваемые элементы (вроде тега ). При этом его внутренняя часть форматируется как блочный элемент, а сам элемент — как встроенный.
inline-table Определяет, что элемент является таблицей как при использовании тега

, но при этом таблица является встроенным элементом и происходит ее обтекание другими элементами, например, текстом.
list-item Элемент выводится как блочный и добавляется маркер списка.
none Временно удаляет элемент из документа. Занимаемое им место не резервируется и веб-страница формируется так, словно элемента и не было. Изменить значение и сделать вновь видимым элемент можно с помощью скриптов, обращаясь к свойствам через объектную модель. В этом случае происходит переформатирование данных на странице с учетом вновь добавленного элемента.
run-in Устанавливает элемент как блочный или встроенный в зависимости от контекста.
table Определяет, что элемент является блочной таблицей подобно использованию тега .).
table-caption Задает заголовок таблицы подобно применению тега .
table-cell Указывает, что элемент представляет собой ячейку таблицы (тег или ).
table-column Назначает элемент колонкой таблицы, словно был добавлен тег .
table-column-group Определяет, что элемент является группой одной или более колонок таблицы, как при использовании тега .
table-footer-group Используется для хранения одной или нескольких строк ячеек, которые отображаются в самом низу таблицы. По своему действию сходно с работой тега .
table-header-group Элемент предназначен для хранения одной или нескольких строк ячеек, которые представлены вверху таблицы. По своему действию сходно с работой тега .
table-row Элемент отображается как строка таблицы (тег
table-row-group Создает структурный блок, состоящий из нескольких строк таблицы аналогично действию тега .

HTML5 CSS 2.1 IE Cr Op Sa Fx

        

<html>
<body>
<b>Формула серной кислоты:</b> <i>H<sub><small>2</small></sub> SO<sub><small>4</small> </sub></i>
</body>
</html>

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

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

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

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

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

Браузеры

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

  • поддержка значений table-footer-group и table-header-group происходит только для тегов и ;
  • для элементов
  • понимает значение block как list-item ;
  • значение inline-block применяется только для встроенных элементов, с блочными элементами работает некорректно.

Opera 9.2, а также Firefox 2.0:

  • значение table-column применяется только для тега ;
  • значение table-column-group поддерживается только для тега .

Chrome 2.0, а также Safari версии 3 и старше, iOS:

  • значение run-in поддерживают только для элементов, которые располагаются перед встроенными элементами или такими, у которых значение display установлено как inline .
  • Значение table-cell не работает, если нет элементов со значениями свойства display : table и table-row .

Источник

Оцените статью