What is the difference between block and inline-block?
When working with HTML (HyperText Markup Language) and CSS (Cascading Style Sheets), a block, inline, and inline-block may be confusing. Below are examples of each attribute to give a better understanding of how each of them work.
CSS display: inline
In our first example, we use a <span> tag, which by default is an inline element. In the example below, the text is red as dictated by the style attribute in the <span> tags. This method is one way to make a few words or a sentence red using CSS.
HTML code:
<span style="color:red;">span text</span>
CSS display: block
In the next example, we've changed the default of the <span> tag to display as a block. Because a block element occupies its own line, it gives the appearance that an enter or return was pressed after "how" and "text" in our example.
Example text to give an example of how to make span text inline, block, or inline-block element and how it changes the appearance of text.
HTML code:
<span style="color:red; display: block;">span text</span>
CSS display: inline-block
Finally, in the next example, we've changed the default of the <span> tag to display as an inline-block. Unlike a block element an inline-block remains inline with all text around the element and appears the same as an inline.
Example text to give an example of how to make span text inline, block, or inline-block element and how it changes the appearance of text.
HTML code:
<span style="color:red; display: inline-block;">span text</span>
Why would I use an inline-block instead of inline?
After seeing the examples above, you may immediately ask yourself why would I want to use a block or inline-block element? By making an element a block element, you get the ability to have a vertical height to that element, as shown below.
Inline span with height
Example text to give an example of how to make span text inline, block, or inline-block element and how it changes the appearance of text.
HTML code:
<span style="color:red; background-color:yellow; height:60px;">span text</span>
Inline-block span with height
Example text to give an example of how to make span text inline, block, or inline-block element and how it changes the appearance of text.
HTML code:
<span style="color:red; background-color:yellow; display: inline-block; height:60px;">span text</span>