HTML | Understanding display

HTML | Understanding display

Everything in HTML has a box around it and depending on the element they might have their own widths, heights, padding, and margins. Understanding these boxes is key in creating amazing layouts.
The display property specifies the display behavior of these elements. In HTML, the default display property value is taken from the HTML specifications or from the browser/user default style sheet.
there are about 23 different display values, but in this article, I'd like to focus on just these 4

  • Block

  • Inline

  • Inline-Block

  • none

Before we proceed let us refresh our memory about the Box Model by observing the following diagram

2020-11-29.png

Block

Block means that the element is displayed as a block, as paragraphs and headers have always been. A block has some whitespace above and below it, and tolerates no HTML elements besides it, except when ordered otherwise.
you can convert a given element to a block by targeting it with a class, id, or tag and changing its default display property.
syntax:
display: block;

inline

inline means that the element is displayed in line, inside the current block on the same line. Only when it's between two blocks does the element form an 'anonymous block', that however has the smallest possible width.
In an inline-level element,

  • You cannot change the width and Height.

  • You can add left and right padding, but the top and bottom padding have the tendency to blend with the above and below elements.

  • You can add left and right borders, but the top and bottom border have the tendency to blend with the above and below elements.

  • You can add left and right margins, but the top and bottom margins have the tendency to blend with the above and below elements.
    syntax:
    display: inline;

2020-11-29 (1).png

inline-block

Compared to inline, the major difference is that inline-block allows to set a width and height on the element.
Compared to block, the major difference is that inline-block does not add a line-break after the element, so the element can sit next to other elements.
In an inline-level element,

  • You can change the Width and Height of the element.

  • You can add left and right padding, as well as top and bottom padding.

  • You can add left and right borders, as well as top and bottom borders.

  • You can add left and right margin, as well as top and bottom margin.
    syntax:
    display: inline-block;

none

here the element is completely removed. It does not exist on the DOM tree.
the difference between display: none and visibility:hidden; is that " visibility:hidden; " hides an element. However, the element will still take up the same space as before. The element will be only not visible therefore it will still affect the layout.
syntax:
display: none;

Summary

display_property.png