Свойство display в CSS используется для настройки отображения элемента. Он управляет и изменяет способ отображения элементов HTML на веб-странице.
Каждый элемент, отображаемый на странице, имеет свое свойство display. Оно может быть либо присвоенным по-умолчанию, либо присвоенное специально программистом.
Прежде чем перейти к конкретным свойствам display, мы рассмотрим, что такое блочные и строчные элементы.
Элемент блочного уровня всегда начинается с новой строки и занимает всю доступную ширину. Теги , , , в HTML — это теги, которые отображаются как «блок».
Строчный элемент не начинается с новой строки и занимает только необходимую ширину. Теги , , , в HTML — это теги, которые отображаются как строчные.
Основные значения свойства display
Давайте теперь рассмотри различные свойства display.
Inline
Используется для отображения строчного элемента. Строковые элементы отображаются в одну строку, т. е. горизонтально, и занимают столько ширины, сколько необходимо. Строковые элементы игнорирует высоту и ширину, заданные пользователем. Примерами встроенных элементов являются теги , , и .
Боксы выше расположены горизонтально в одну строку. Несмотря на то, что мы установили высоту и ширину блоков — свойство inline игнорирует это. Поэтому боксы занимают строго столько места, сколько необходимо для размещения текста внутри них
Block
Свойство block используется для отображения блочных элементов. Блочные элементы располагаются один по другим. Для них можно менять высоту и ширину. Если ширина явно не указано, то блочный элемент займет всю ширину родительского контейнера.
Рассмотрим пример тремя боксами, обернутыми в родительский контейнер.
Blue box
Red box
Green box
Явно указываем ширину только для box—blue, для остальных боксов указываем только высоту.
Мы видим, что все элементы расположились друг под другом. Синий бокс имеет фиксированную ширину и высоту, так как мы ее явно задали. Остальные боксы тянутся по ширину на весь родительский контейнер (для наглядности добавил внутренний отступ padding).
Inline-block
Свойство inline-block относится к блочно-строчным элементам. Выше мы видели, что строчные элементы располагаются рядом друг с другом, а их высота и ширина, заданные явно, не отображаются. При этом блочные элементы отображают, заданные нами размеры.
Свойство inline-block позволяет размещать элементы в строке, но при этом явно задавать им ширину и высоту. По сути inline-block является комбинацией двух свойств: inline и block.
Flex используется для отображения элемента в виде гибкого контейнера. Отображение элементов начинается с начального края главной оси. Главная ось определяется свойством flex-direction, которое может определять как вертикальное, так и горизонтальное направление flex-элементов.
Grid
Grid используется для отображения элемента как контейнера сетки.
Inherit
Inherit нужен для наследования свойства display элемента от его родительских элементов. Используется когда мы создаем вложенные элементы (например внутри ). Вместо того, чтобы каждый раз указывать свойство display дочернего элемента, мы можем просто наследовать его от родительского.
Initial
Initial используется для установки свойства display в значение по умолчанию. Начальное значение можно использовать для восстановления всех свойств CSS. Например: если мы установим display со значением initial для элемента , то элемент будет отображаться как блочный (по умолчанию).
Вывод
Свойство display в CSS используется для настройки отображения элемента.
Display управляет и изменяет способ отображения элементов HTML на веб-странице.
Отображаемое значение по умолчанию для большинства элементов — блочное или встроенное.
Наиболее важными значениями свойств являются inline, block, inline-block и none.
The CSS Display Property – Display None, Display Table, Inline Block and More
Kolade Chris
In CSS, the display property determines how an element looks. It is also a crucial part of the presentation of you HTML code as it has a significant impact on layouts.
In fact, to use the modern Flexbox and Grid models, you need to use the display property before you get access to their various properties and values. This is one reason why the display property is so important in CSS.
Let’s dive in and learn how to use the display property and all its different values.
Basic display Property Syntax
Display Property Values in CSS
There are inline and block-level elements in CSS. The difference between the two is that inline elements don’t take up an entire space – that is, they don’t start on a new line – but block elements do.
The display property takes many different values such as inline , inline-block , block , table , and more, which all influence the layout and presentation of an element on the web page. Also, to implement the flex and grid layouts, you need to use the display property.
You can use this display property to change an inline element to block , block element to inline , block and inline elements to inline-block , and many more.
display: inline
An element with a display property set to inline will not start on a new line and it will take up the remaining/available screen width. It just takes up the space such an element would normally take.
Because of this, you can’t set the width and height of an element that has a display of inline , becuase it does not take up the whole screen width.
Some elements are inline by default, like , , , and .
Lorem ipsum dolor sit amet consectetur adipisicing elit. This is an inline lement Modi eaque debitis eos quod labore maiores delectus asperiores voluptatem voluptas soluta!
display: block
An element that has the display property set to block starts on a new line and takes up the available screen width.
You can specify the width and height properties for such elements. Examples of elements that are at block-level by default are , ,
, and lots more.
You can set the span from the previous HTML code to block display and it will behave like a block-level element.
You can see that the takes up the full width. That’s because it has a display property set to block.
display: inline-block
Apart from block and inline display, there’s also inline-block.
An element you assign a display of inline-block is inline by presentation. But it has the added advantage of you being able to apply width and height to it, which you can’t do when the element is assigned a dispaly of inline .
So, you can look at the inline-block display as an inline element and block element in one package.
display: none
When you set the display property of an element to none , the element is completely taken off the page and it doesn’t have an effect on the layout.
This also means that devices like screen readers, which make websites accessible to blind people, wont’t have access to the element.
Do not confuse display: none with visibility: hidden . The latter also hides the element, but leaves the space it would normally take open or empty.
Visibility hidden leaves the space occupied by the span element open, as you can see below:
display: table
You’ll rarely use a display value of table these days, but it’s still important to know. It was more useful in the past because you would use it for layouts before the advent of floats, Flex, and Grid.
Setting display to table makes the element behave like a table. So you can make a replica of an HTML table without using the table element and corresponding elements such as tr and td .
Fruits
Lemurs
Pets
Cashew
Hua hua
Dog
Apple
Diadem Sifaka
Cat
Mango
Rig-tailed
Chicken
The result of the HTML and CSS code snippets above looks like this:
But you can make the same table with the element by setting the respective displays to table , table-row , and table-cell . You will get the same result as you can see below:
Apart from inline , block , none , and table , which are really important because they significantly influence how web pages look, there are other values of the display property worthy of your attention.
Some of them you’ll use all the time without really realizing that they are also part of the display property. And others you won’t use often at all.
Let’s look at some of them now.
display: flex
A display of flex gives you access to the Flex layout system, which simplifies how we design and layout our web pages.
Lorem ipsum dolor sit amet consectetur adipisicing elit. This is an inline element Modi eaque debitis eos quod labore maiores delectus asperiores voluptatem voluptas soluta!
Lorem ipsum dolor sit amet consectetur adipisicing elit. This is an inline element Modi eaque debitis eos quod labore maiores delectus asperiores voluptatem voluptas soluta!
display: grid
A display set to grid allows you to build layouts with the grid system, which is like an advanced form of flex.
Lorem ipsum dolor sit amet consectetur adipisicing elit. This is an inline element Modi eaque debitis eos quod labore maiores delectus asperiores voluptatem voluptas soluta!
Lorem ipsum dolor sit amet consectetur adipisicing elit. This is an inline element Modi eaque debitis eos quod labore maiores delectus asperiores voluptatem voluptas soluta!
display: inherit
This makes the element inherit the display property of its parent. So, if you have a tag inside a div and you give the span tag a display of inherit , it turns it from inline to block element.
Lorem ipsum dolor sit amet consectetur Inline element adipisicing elit. Cumque cupiditate harum consectetur a exercitationem laboriosam nobis eos pariatur expedita iure.
display: initial
This sets the display property of an element to its default value. So, if you set the display property of a span to initial, it remains inline, and if you set the same value for a div, it remains block.
Lorem ipsum dolor sit amet consectetur Inline element adipisicing elit. Cumque cupiditate harum consectetur a exercitationem laboriosam nobis eos pariatur expedita iure.
Conclusion
Having a good grasp of the display property will help your page layouts look great. It also gives you a lot more control over the way you present your elements while working with CSS.
You can continue to come back to this article for reference too as the display property is always confusing at first until you use it enough to understand it fully.
I hope this article has given you the background knowledge you need in order to put the display property to good use.