Block and Inline Elements Explained - With Examples
HTML elements are categorized into block-level and inline elements. This categorization has left a lot of new web developers confused.
Understanding the difference between the block level and inline elements is very useful because it guides you towards styling HTML elements in the right way.
In this article, I will explain the difference between block and inline elements with examples.
Block-level elements occupy the available space with their parent element (container), thereby creating a block. These elements usually start on a new line, and any other element following them appears on its own new line.
A paragraph is a type of block element. I will use it to shed more light on block-level elements.
The code snippet below contains two paragraphs. As you can see, the first paragraph took up as much horizontal space as possible and pushed the second paragraph down to a new line.
This means that block-level elements are stacked vertically instead of horizontally. So if you want the elements on your webpage to be displayed horizontally without any serious manipulation, use an inline element.
Unlike block elements, inline elements do not take up the available space in the parent element (container). Inline elements can be added between block elements without pushing the element after it to the next line.
A span is an example of an inline element. You will see how it is different from the paragraph tag.
From the code snippet above, the span elements are stacked horizontally first and will only be pushed vertically when there's no other space horizontally.
How to Change the Category of Elements
It's also important to note that you can change block elements to inline elements and vice versa using the code snippet below:
For instance, if you want to change the paragraph tag which is originally a block element to an inline element, you need to set the
display attribute to
Let's try it out!
As explained above, I added the
display:inline attribute to paragraph element. So if you click on the button, you will see the change.
I hope this article was helpful. If so, share this article and follow @didicodes on Twitter.