- CSS Layout — The display Property
- The display Property
- Block-level Elements
- Inline Elements
- Display: none;
- Override The Default Display Value
- Example
- Example
- How to display user entered information using HTML and JavaScript
- How to display user entered information using HTML and JavaScript
- How to display user entered information using HTML and JavaScript.
- Tutorials
- Все значения свойства display
- Значение none
- Значение block
- Значение inline
- Значение inline-block
- Значения table-*
- Вертикальное центрирование с table-cell
- Значения list-item, run-in и flex
- Display
- Inline
- Block
- None
- Tables
- Other display types
- Related pages
- Examples
- References
CSS Layout — The display Property
The display property is the most important CSS property for controlling layout.
The display Property
The display property specifies if/how an element is displayed.
Every HTML element has a default display value depending on what type of element it is. The default display value for most elements is block or inline .
This panel contains a element, which is hidden by default ( display: none ).
It is styled with CSS, and we use JavaScript to show it (change it to ( display: block ).
Block-level Elements
A block-level element always starts on a new line and takes up the full width available (stretches out to the left and right as far as it can).
Examples of block-level elements:
Inline Elements
An inline element does not start on a new line and only takes up as much width as necessary.
This is an inline element inside a paragraph.
Examples of inline elements:
Display: none;
display: none; is commonly used with JavaScript to hide and show elements without deleting and recreating them. Take a look at our last example on this page if you want to know how this can be achieved.
The element uses display: none; as default.
Override The Default Display Value
As mentioned, every element has a default display value. However, you can override this.
Changing an inline element to a block element, or vice versa, can be useful for making the page look a specific way, and still follow the web standards.
Example
Note: Setting the display property of an element only changes how the element is displayed, NOT what kind of element it is. So, an inline element with display: block; is not allowed to have other block elements inside it.
The following example displays elements as block elements:
Example
The following example displays elements as block elements:
How to display user entered information using HTML and JavaScript
We are going to describe How to display user entered information using HTML and JavaScript. First of all we have created HTML form with two text fields «FirstNames» and «LastName». A submit button is created that will be used to submit the information entered in first two text fields.
How to display user entered information using HTML and JavaScript
How to display user entered information using HTML and JavaScript.
We are going to describe How to display user entered information using HTML and JavaScript. First of all we have created HTML form with two text fields «FirstNames» and «LastName». A submit button is created that will be used to submit the information entered in first two text fields. We have used javaScript and document.getElementById(«displayarea») method to get id. The id given to an HTML input helps in accessing the entered information in that field very quickly. It checks the text entered in the text field, gets the value and displays it.
element = document.getElementById(id);
function display()
FirstNames |
Fast Name | Last Name |
output:- Tutorials
Все значения свойства displayСвойство display имеет много разных значений. Обычно, используются только три из них: none , inline и block , потому что когда-то браузеры другие не поддерживали. Но после ухода IE7-, стало возможным использовать и другие значения тоже. Рассмотрим здесь весь список. Значение noneСамое простое значение. Элемент не показывается, вообще. Как будто его и нет. Значение block
Это значение display многие элементы имеют по умолчанию: , заголовок , параграф . Блоки прилегают друг к другу вплотную, если у них нет margin . Значение inline
Например, инлайновые элементы по умолчанию: , . Если вы присмотритесь внимательно к примеру выше, то увидите, что между внутренними и есть пробел. Это потому, что он есть в HTML. Если расположить элементы вплотную – его не будет: Содержимое инлайн-элемента может переноситься на другую строку. При этом каждая строка в смысле отображения является отдельным прямоугольником («line box»). Так что инлайн-элемент состоит из объединения прямоугольников, но в целом, в отличие от блока, прямоугольником не является. Это проявляется, например, при назначении фона. Например, три прямоугольника подряд: Если инлайн-элемент граничит с блоком, то между ними обязательно будет перенос строки: Значение inline-blockЭто значение – означает элемент, который продолжает находиться в строке ( inline ), но при этом может иметь важные свойства блока. Во всём остальном – это блок, то есть: Это значение display используют, чтобы отобразить в одну строку блочные элементы, в том числе разных размеров. Свойство vertical-align позволяет выровнять такие элементы внутри внешнего блока: Как и в случае с инлайн-элементами, пробелы между блоками появляются из-за пробелов в HTML. Если элементы списка идут вплотную, например, генерируются в JavaScript – их не будет. Значения table-*Современные браузеры (IE8+) позволяют описывать таблицу любыми элементами, если поставить им соответствующие значения display . Для таблицы целиком table , для строки – table-row , для ячейки – table-cell и т.д. Важно то, что это действительно полноценная таблица. Используются табличные алгоритмы вычисления ширины и высоты элемента, описанные в стандарте. Это хорошо для семантической вёрстки и позволяет избавиться от лишних тегов. table < display: table >tr < display: table-row >thead < display: table-header-group >tbody < display: table-row-group >tfoot < display: table-footer-group >col < display: table-column >colgroup < display: table-column-group >td, th < display: table-cell >caption Очень подробно об алгоритмах вычисления размеров и отображении таблиц рассказывает стандарт CSS 2.1 – Tables. Вертикальное центрирование с table-cellВнутри ячеек свойство vertical-align выравнивает содержимое по вертикали. Это можно использовать для центрирования: CSS не требует, чтобы вокруг table-cell была структура таблицы: table-row и т.п. Может быть просто такой одинокий DIV , это допустимо. При этом он ведёт себя как ячейка TD , то есть подстраивается под размер содержимого и умеет вертикально центрировать его при помощи vertical-align . Значения list-item, run-in и flexУ свойства display есть и другие значения. Они используются реже, поэтому посмотрим на них кратко: Этот display по умолчанию используется для элементов списка. Он добавляет к блоку с содержимым ещё и блок с номером(значком) списка, который стилизуется стандартными списочными свойствами: Если после run-in идёт block , то run-in становится его первым инлайн-элементом, то есть отображается в начале block . Если ваш браузер поддерживает это значение, то в примере ниже h3 , благодаря display:run-in , окажется визуально внутри div : Если же вы видите две строки, то ваш браузер НЕ поддерживает run-in . Вот, для примера, правильный вариант отображения run-in , оформленный другим кодом: Если этот вариант отличается от того, что вы видите выше – ваш браузер не поддерживает run-in . На момент написания этой статьи только IE поддерживал display:run-in . Flexbox позволяет удобно управлять дочерними и родительскими элементами на странице, располагая их в необходимом порядке. Официальная спецификация находится здесь: CSS Flexible Box Layout Module DisplayA key trick to the manipulation of HTML elements is understanding that there’s nothing at all special about how most of them work. Most pages could be made up from just a few tags that can be styled any which way you choose. The browser’s default visual representation of most HTML elements consist of varying font styles, margins, padding and, essentially, display types. The most fundamental types of display are inline, block and none and they can be manipulated with the display property and the shockingly surprising values inline , block and none . Inlineinline does just what it says — boxes that are displayed inline follow the flow of a line. Anchor (links) and emphasis are examples of elements that are displayed inline by default. The following code, for example, will cause all list items in a list to appear next to each other in one continuous line rather than each one having its own line: Blockblock makes a box standalone, fitting the entire width of its containing box, with an effective line break before and after it. Unlike inline boxes, block boxes allow greater manipulation of height, margins, and padding. Heading and paragraph elements are examples of elements that are displayed this way by default in browsers. The next example will make all links in “nav” large clickable blocks: display: inline-block will keep a box inline but lend the greater formatting flexibility of block boxes, allowing margin to the right and left of the box, for example. Nonenone , well, doesn’t display a box at all, which may sound pretty useless but can be used to good effect with dynamic effects, such as switching extended information on and off at the click of a link, or in alternative stylesheets. The following code, for example, could be used in a print stylesheet to basically “turn off” the display of elements such as navigation that would be useless in that situation: display: none and visibility: hidden vary in that display: none takes the element’s box completely out of play, whereas visibility: hidden keeps the box and its flow in place without visually representing its contents. For example, if the second paragraph of 3 were set to display: none , the first paragraph would run straight into the third whereas if it were set to visibility: hidden , there would be a gap where the paragraph should be. TablesOK. So that was the basics. Now for something a little more advanced and rarely used… Perhaps the best way to understand the table-related display property values is to think of HTML tables. table is the initial display and you can mimic the tr and td elements with the table-row and table-cell property values respectively. The display property goes further by offering table-column , table-row-group , table-column-group , table-header-group , table-footer-group and table-caption as values, which are all quite self-descriptive. The immediately obvious benefit of these values is that you can construct a table by columns, rather than the row-biased method used in HTML. Finally, the value inline-table basically sets the table without line breaks before and after it. Be careful when using these values. Older browsers struggle with them and getting carried away with CSS tables can seriously damage your accessibility. HTML should be used to convey meaning, so if you have tabular data it should be arranged in HTML tables. Using CSS tables exclusively could result in a mash of data that is completely unreadable without the CSS. Bad. And not in a Michael Jackson way. Other display typeslist-item displays a box in the way that you would usually expect an li HTML element to be displayed. To work properly then, elements displayed this way should be nested in a ul or ol element. run-in makes a box either in-line or block depending on the display of its parent. Related pages
ExamplesReferences |