HTML's Block vs Inline elements: What they don't tell you
I often have the chance to have coding sessions at Codementor with mentees that are new to HTML and CSS. And one of the things I like to talk about in our first session is something that may sound complex at first, but that to my understanding is one of those things you HAVE to know when coding web pages: Block and Inline elements.
What are Block and Inline elements
In HTML you have a long list of basic elements, known as tags. These tags have a default way to display on a page (that is, before any styling with CSS affects them). And depending on the way they display by default, they belong to one of these two categories.
A block-level element always starts on a new line and takes up the full width of its parent element. In other words, it stretches to the sides as much as it can.
Some example block-level elements are:
An inline element, in contrast, does not start on a new line, and only takes up as much width as the content inside it.
Some example inline-level elements are:
Why should we care?
One of the reasons to care about these is that, in order to keep our code standard-compliant and semantic, and avoid issues with our code, we need to know some rules associated to block and inline elements.
When nesting HTML tags, for instance, you need to keep in mind this rule of thumb:
- Both block and inline elements can be nested inside block elements;
- Inline element can be nested inside block and inline element;
- Block element cannot be nested inside an inline element;
Mixing these up can usually lead to undesired visual results, overly compensated styling with extra CSS, etc.
It is also useful to notice that most of the block-level tags are structural elements, while inline elements are more "content-related". Keep these in mind when choosing your tags!
More on HTML elements
This topic might seem trivial at first, but there is a lot more to it. Knowing your tags as a web developer is knowing the basic tools you will be working with. They will be your swiss knife when you are out there turning designs into beautiful code, and so understanding them in depth will help you stand out and make a difference in your development career.
We can go over this and other topics in a live, 1:1 mentoring session on Codementor.