Home >Web Front-end >CSS Tutorial >Stop Overusing Divs! A Practical Guide to Semantic HTML Best Practices
This guide explores the advantages of using semantic HTML elements over divs. Let's examine a few practical examples.
Why choose semantic tags over divs? The benefits are significant:
Example: A Typical Semantic HTML Structure
Here's a common HTML boilerplate showcasing semantic elements:
<code class="language-html"><header> <img alt="Stop Overusing Divs! A Practical Guide to Semantic HTML Best Practices" src="logo.png"> <nav> <ul> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> </ul> </nav> </header> <main> <h2>About Us</h2> <p>Lorem ipsum...</p> <h2>How It Works</h2> <p>Lorem ipsum...</p> <aside>Sidebar content...</aside> </main> <footer> <p>Terms & Conditions</p> </footer></code>
Explanation:
<header></header>
: Contains the logo and primary navigation.<nav></nav>
: Houses the main navigation links.<main></main>
: Encloses the primary content of the page.<h2></h2>
and <p></p>
: Structure the main content logically.<aside></aside>
: Represents secondary content, like a sidebar.<footer></footer>
: Includes less crucial information, such as terms and conditions.MDN Web Docs Example
Observe the structure of MDN's JavaScript guide page:
<code class="language-html"><main> <h1>JavaScript Guide</h1> <p>Learn JavaScript...</p> <nav> <ul> <li><a href="#toc">Table of Contents</a></li> </ul> </nav> </main></code>
Key takeaways:
<main></main>
element clearly defines the core content. It's self-contained and reusable.<main></main>
section as it's crucial to the guide's usability.When to Use divs
Use divs only for styling or layout when no semantic element accurately reflects the content's meaning.
<code class="language-html"><div> <p>Why a div here? The info-bar groups unrelated elements (breadcrumbs and a button) purely for layout; they lack a shared semantic purpose.</p> <h2>Summary</h2> <p>Use semantic tags when:</p> <ul> <li>Content is related (<article>).</article> </li> <li>It's self-contained (<article>).</article> </li> <li>It's critical navigation (<nav>).</nav> </li> <li>It's secondary content (<aside>).</aside> </li> </ul> <p>Use divs when: You need a container solely for styling.</p> <p>If you found this helpful, please like and follow! Thanks for reading!</p> <p>Connect with me on:</p> <p><strong>LinkedIn</strong> | <strong>Medium</strong> | <strong>Bluesky</strong></p> </div></code>
The above is the detailed content of Stop Overusing Divs! A Practical Guide to Semantic HTML Best Practices. For more information, please follow other related articles on the PHP Chinese website!