Alright, in this guide, we’ll discuss why and when to use semantic HTML elements over divs. Alright, so I just have a couple of examples for you.
First of all, why do we even want to use semantic tags instead of divs? Well:
- It’s easier to read and scan the HTML if it’s properly structured with semantic tags (I’ll show you why in a second).
- Better for SEO: It makes it easier for search engines like Google to index your content, which helps you rank higher and get more traffic.
- Better for screen readers/assistive tech to categorize and index your website.
- Accessibility: It’s just better overall.
These are the three—well, four—main reasons.
Typical Semantic HTML Boilerplate
Let me give you an example. Here’s a typical HTML boilerplate:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<header>
<img src="logo.png" alt="Logo">
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
</nav>
</header>
<main>
<section>
<h2>About Us</h2>
<p>Lorem ipsum...</p>
</section>
<section>
<h2>How It Works</h2>
<p>Lorem ipsum...</p>
</section>
<aside>Sidebar content...</aside>
</main>
<footer>
<p>Terms & Conditions</p>
</footer>
</body>
</html>
Breakdown:
-
<header>
: Logo, introductory links. -
<nav>
: Main navigation (like that list of links). -
<main>
: Dominant content. -
<section>
: Groups related content (e.g., "About Us" and "How It Works"). -
<aside>
: Sidebar or secondary content. - : Less important links (terms, privacy policy).
MDN Web Docs Example
On MDN’s JavaScript guide page:
<main>
<article>
<h1>JavaScript Guide</h1>
<p>Learn JavaScript...</p>
</article>
<aside>
<nav>
<ul>
<li><a href="#toc">Table of Contents</a></li>
</ul>
</nav>
</aside>
</main>
Key points:
-
<article>
: The guide is self-contained. You could republish it elsewhere, and it’d still make sense. -
<aside>
: The sidebar navigation isn’t part of the main content. -
<nav>
in the footer? Nope. MDN uses it in the<aside>
because it’s critical navigation.
When to Use divs
Use divs for styling/layout when no semantic meaning exists.
<div class="info-bar">
<section class="breadcrumbs">
<a href="/">Home</a> > <a href="/guides">Guides</a>
</section>
<button>Sign In</button>
</div>
Why a div
here? The info-bar groups unrelated elements (breadcrumbs and a button) purely for layout. They don’t share a semantic purpose.
Summary
Use semantic tags when:
- Content is related (
<section>
). - It’s self-contained (
<article>
). - It’s critical navigation (
<nav>
). - It’s secondary content (
<aside>
).
Use divs
when: You just need a box for styling.
By the way, if this guide was helpful, I’d really appreciate a big heart and follow! Thanks for reading to the end, and I hope to write for you again!
Stay connected with me on my other platforms:
Top comments (1)
Ouff thank you!!