Block vs Inline Elements
Overview
Every HTML element has a default display behavior. The browser places it on the screen as either a 'Block' or 'Inline' element. Understanding this distinction is the absolute most important concept for mastering CSS layouts later on.
Imagine placing physical objects on a desk. Some objects are like long rulers that take up the entire width of the desk (Block). Other objects are like small coins that just sit side-by-side until they run out of space (Inline).
Syntax
Block elements are greedy. They always start on a brand new line, and they stretch to take up 100% of the available width, even if their text is very short.
Examples of block elements include `<div>`, `<p>`, `<h1>` to `<h6>`, `<ul>`, and `<form>`.
<!-- Both paragraphs take full width. -->
<!-- They stack vertically on top of each other. -->
<p>I am a paragraph.</p>
<p>I am another paragraph on a new line.</p>
<!-- The heading also pushes everything else below it -->
<h1>Main Title</h1>Inline elements are polite. They do NOT start on a new line. They only take up exactly as much width as their content needs, and they sit peacefully side-by-side with other inline elements.
Examples include `<span>`, `<a>` (links), `<strong>`, `<img>`, and `<button>`.
<!-- These links will sit next to each other on the same line -->
<a href="/home">Home</a>
<a href="/about">About</a>
<!-- The span stays inside the paragraph text line -->
<p>This is <span style="color:red">red</span> text.</p>Because block elements are massive and inline elements are small, the rules of HTML state: You can put an inline element INSIDE a block element, but you CANNOT put a block element inside an inline element (with a few rare HTML5 exceptions).
<!-- ✅ CORRECT: Inline link inside a Block paragraph -->
<p>Click <a href="#">here</a>.</p>
<!-- ❌ WRONG: Block paragraph inside an Inline link -->
<a href="#"><p>Click here</p></a>Common Pitfalls
- You cannot set a custom 'width' or 'height' or 'margin-top' on an inline element (like a <span>). The browser will simply ignore it! If you want to give a <span> a width, you have to use CSS to change its display to block (display: block) or inline-block.
- Interview tip: <img> is technically an inline element, but it is a special type called a 'replaced element', which means you CAN set a width and height on it.
Real-World Example
Demonstrating block vs inline behavior in a real UI component:
<!-- Div (Block) creates the outer container -->
<div class="alert-box">
<!-- Span (Inline) keeps the icon and text on the same line -->
<span class="alert-icon">⚠️</span>
<span class="alert-message">Your session is expiring.</span>
<!-- Button (Inline) sits right next to the text -->
<button>Renew Now</button>
</div>