We’ve seen how there are mainly 2 types of HTML elements: block-level elements and inline ones. We’ve also mentioned a few alternatives, like list-item or table-cell.
The display
property allows to change the type of HTML element. By default, a paragraph <p>
(a block-level element) will have a default display
value of block
, but can be rendered as an inline one:
Why not use an HTML inline element, like <span>
then?
Because you choose an HTML element for its meaning, not its rendering. If we’ve decided that a paragraph is what suited our content best, we must not change the tag only for styling purposes. CSS is here to take care of the styling.
In short, display
allows to alter the type of an element without changing its meaning.
Each display
options have specific rendering behaviors:
block
will take up the whole width availableinline
will act as plain textinline-block
is, as its name suggests, a compound of block and inline behavior, a “best of both worlds” optionlist-item
is similar toblock
as it takes up the whole width available, but shows an additional bullet pointtable
,table-row
andtable-cell
all have very specific, albeit unexpected, behavior that allow more interesting layouts
display: block
This will turn any element into a block element.
This technique is often used on links in order to increase their clickable zone, which can be easily evaluated by setting a background color.
If we turn these links into blocks, we increase their target area:
display: inline
This turns any element into inline elements, as if they were just simple text.
It’s often used to create horizontal navigations, where list items are semantically but not visually useful.
display: list-item
The only HTML elements displayed as list-item
are the (unsurprisingly) list items <li>
but also the definition descriptions <dd>
.
A list item is rendered with a bullet point (if in an unordered list <ul>
) or with a incremental number (if within an ordered list <ol>
).
Because the rendering of these bullet points and numbers varies across browsers, and is also hard to style in CSS, the display: list-item
rule is never used. Actually, it is common for <li>
s to be rendered as display: block
or display: inline
, as they are more flexible to style.
display: none
Applying display: none;
to an HTML element removes it from your webpage, as if it never existed in your code.
Did I hear someone speaking??
I must be dreaming...
There are 3 paragraphs in the code, but only 2 appear, as if the 2nd one never existed.
visibility: hidden
The CSS property visibility
is slightly similar to display
. Applying visibility: hidden;
hides an element from your page, but only turns it invisible: it still takes up the space it was supposed to.
So far away from me
You're so far away...
There are 5 paragraphs in the code, only 2 appear, but the space that the hidden paragraphs were supposed to take is still there, but you can’t see them.