How to use the HTML <div> Element

Learn how to use the HTML <div> element.

The <div> element is a generic container element that is used to divide, group, and encapsulate content.

You should only use the <div> element use if no semantic HTML elements make sense to use relative to the context (or if you’re not sure).

Semantic markup is when you use HTML elements that describe the meaning/function of the content you put inside. The <div> element is a generic/un-semantic element.

Use cases for the <div> element

Let’s say you’re coding a reusable modal component for your website, that encourages your site visitors to subscribe to your newsletter.

There’s no pre-existing semantic HTML tag to define such a component, so that is a perfect example of when to use the generic <div> container element:

<div class="subscribe-modal">
  <form id="contact" method="post" action="">
    <fieldset>
      <h3>Subscribe to my Newsletter</h3>
      <input
        name="email"
        id="email"
        type="email"
        placeholder="Enter your email address here"
        required
      />
      <input type="submit" name="submit" class="submit" value="Subscribe!" />
    </fieldset>
  </form>
</div>

The <div> tag is one of many HTML tags used to define container elements. Some of the most commonly used HTML container elements are:

<article>,<section>, <main> , <header>, <footer>,<form>.

If any of the elements above make sense to use as containers for your content, then use them rather than the generic <div>.

Why? Because they are all semantic element tags while <div> is an un-semantic tag, that doesn’t provide any specific context.

Good to know about the <div> element

You can put any type of content inside the <div> element.

Although semantic markup is generally recommended, it’s not required for browsers to understand and render your page to the user.

However, if you use generic/un-semantic HTML elements in situations where HTML already has semantic tags for you to use, it might hurt your SEO.

Generally, I’d use the <div> element if I wasn’t sure about which HTML element to use because I’d rather use a generic element than the wrong element. Besides, you can’t really use the <div> element incorrectly from a technical point of view — only from a semantic point of view.


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on