The display property is perhaps one of the most important properties in CSS.
Every element in an HTML document is treated as a box, and it’s the display property that determines how these boxes will be shown.
There are a large amount of values that can be used with this property. However, only some of them of commonly used, we’ll be focusing on these:
inline
inline-block
block
flexbox
grid
none
table
Inline
The inline value is the default for every element in CSS.
display: inline;
A neat way to visualize inline is to think of a paragraph containing some words in wrapped in bold or tags.
We can apply padding and margins to inline elements, however the surrounding elements will be pushed aside in a horizontal direction (not vertical). Also, height
and width
are ignored by inline
elements.
Every HTML tag is displayed inline unless otherwise specified, with a few exceptions such as div
, p
and section
, which are set as block
.
Inline-block
display: inline-block;
An element with inline-block
is very similar to inline
, however the width
and height
are able to be applied as specified.
Block
display: block;
As mentioned, a number of elements are set to block
by default. They are layout elements, such as <div>
, <section>
, and <ul>
. Also text elements such as <p>
and <h1>
.
Block level elements are stacked one after each other in a vertical direction. By default each element takes up 100% of the page width.
If specified, the values assigned to the width
and height
as well as margin
and padding
are all adhered to.
Flexbox
The display
property is also used when working with flexbox:
display: flex;
Grid
When using CSS Grid, we also set the display property:
display: grid;
None
display: none;
We use display: none
to make an element disappear.
It’s still loaded in our HTML, just not rendered visible by the browser.
Table Values
display: table;
With the advent of modern layout methods such as flexbox & grid, the <table>
HTML element is a bit of a relic.
However, we could use a number of display values to get non-table elements to behave like table elements, if we’re so inclined:
element {
display: table;
display: table-cell;
display: table-column;
display: table-row;
display: table-caption;
}
We could use this like so:
<div style="display: table;">
<div style="display: table-row;">
<div style="display: table-cell;">
Cell content.
</div>
</div>
</div>
It’s not a common technique as it makes for messy markup, however it may have the odd use-case.
Conclusion
If you liked this blog post, follow me on Twitter where I post daily about Tech related things!
If you enjoyed this article & would like to leave a tip — click here
Top comments (0)