HTML Div, Span & Layout Basics
When you’re building any layout in HTML, you’ll often need to group content, apply CSS styling, or structure your page for flexibility.
That’s where block vs inline, and two very important tags—<div>
and <span>
—come in!
Let’s simplify the whole thing.
🧱 Block vs Inline Elements
Block-level elements always start on a new line and take up the full width available.
Inline elements flow within the line of text and only take up as much width as needed.
Block Elements | Inline Elements |
---|---|
<div> | <span> |
<p> | <a> |
<h1> to <h6> | <strong> , <em> |
<ul> , <ol> , <li> | <img> , <input> |
🧪 Example:
<p>This is a <strong>block</strong> vs <em>inline</em> demo.</p>
<div style="background: #f3f3f3;">I am a block element.</div>
<span style="background: yellow;">I am inline.</span>
📌 Using <div>
– Block Container
<div>
stands for division. It’s a block-level element used to group other HTML elements together.
It’s mostly used for:
- Layout structure
- CSS styling
- JavaScript targeting
Example:
<div class="header">
<h1>Welcome to My Site</h1>
</div>
<div class="content">
<p>This is a paragraph inside a div.</p>
</div>
You’ll often see this structure:
<div class="wrapper">
<div class="header">...</div>
<div class="main">...</div>
<div class="footer">...</div>
</div>
📌 Using <span>
– Inline Container
<span>
is used to style or group inline text or parts of elements without breaking flow.
Example:
<p>My favorite color is <span style="color: blue;">blue</span>.</p>
You wouldn’t use a <div>
here because that would break the line.
✅ When to Use Div or Span
Use Case | Use |
---|---|
Group layout blocks | <div> |
Style or target part of text | <span> |
Wrap content for JavaScript | Both work |
Semantic layout (modern HTML5) | Prefer sectioning tags like <section> , <article> over <div> when possible |
🧠 Grouping & Identifying Content
Even though <div>
and <span>
are “non-semantic” (they don’t describe meaning), they’re incredibly useful for:
- Wrapping content to apply CSS styles
- Making reusable components
- Structuring a page visually
- JavaScript interactions via
id
orclass
Example with IDs & Classes:
<div id="card" class="box highlight">
<h2>Card Title</h2>
<p>This is the body of the card.</p>
</div>
⚠️ Tip:
Don’t overuse <div>
and <span>
. Use them when no semantic tag fits (like <section>
, <article>
, <nav>
, etc.).
📌 Summary
Tag | Type | Purpose |
---|---|---|
<div> | Block-level | Group large sections |
<span> | Inline | Group inline content/text |
class | – | Apply styling across elements |
id | – | Unique identifier per element |
📚 Coming Up Next:
You’ve just learned the tools to layout content visually and group things for styling or scripting.
📘 Next Topic: Semantic HTML Elements