21. Block vs Inline (Block vs Inline Deep Dive)
The nature of elements on screen: taking up the whole line or sitting side by side
Real-life analogy
A block element is like a big brick that takes up the full width of the wall, while an inline element is like a thread that flows along with the words on the same line.
Explanation
Every element in the browser has a default display behaviour:
1. Block-level Elements:
- Always start on a new line.
- Take up the full 100% width of the screen.
- CSS Width, Height, Margin and Padding work on them.
- E.g.:
<div>,<p>,<h1>-<h6>,<ul>,<form>
2. Inline Elements:
- Do not start on a new line; they sit side by side on the same line.
- Take up only as much width as the content needs.
- Width and Height do not work directly on them.
- E.g.:
<span>,<a>,<strong>,<img>
Golden rules
- Never put a large block element inside an inline element.
Common mistake
Trying to apply width to an inline element with CSS (it doesn't work unless you set display: inline-block).
Example code
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; padding: 20px;">
<div style="background-color: #fed7aa; border: 2px solid #f97316; padding: 8px; margin-bottom: 8px;">
This is a <strong><div></strong> (Block): it takes up the full width.
</div>
<p>
This is a normal sentence in which
<span style="background-color: #bbf7d0; border: 1px solid #22c55e; padding: 2px 6px;">
<span> (Inline)
</span>
and a
<a href="#" style="background-color: #bfdbfe; padding: 2px 6px; color: #1d4ed8;">
<a> link
</a>
are sitting side by side on the same line!
</p>
</body>
</html>
Quick quiz
Which of these is a block-level element?
- <span>
- <a>
- <div>
- <strong>
Show answer
Answer: <div>
<div> is a block-level element that takes up the whole line.