Skip to main content

Self-closing elements in HTML

Posted in Development and HTML

I covered the most common type of element in my article on tags versus elements, where an element is made up of:

  • an opening tag
  • a closing tag
  • all of the content in between

But I’m sure you’ve used an image before, and they don’t look like that! This is where the distinction between tags and elements gets a bit blurry – some elements are tags!

An image is just an opening tag. No closing tag; no content inside. This type of element is known as ‘self-closing’ (or sometimes ‘void’) and look like this:

<img src="/img/my-great-image.jpg" alt="My alt text" />

So they’re just a tag with some attributes and a forward slash right before the end.

It’s not just images. You’ll have used plenty of <input /> elements, I’m sure. And up there in your document’s <head>, there’re probably plenty of <meta /> elements and the odd <link />. You might even use <br /> and <hr /> every now and again (although, I have opinions on break tags and horizontal rules).

I should mention that the / at the end is optional (well, it is in HTML5). You can write your image element image without one, like this:

<img src="/img/my-great-image.jpg" alt="My alt text">

But I always use the ‘trailing’ slash. It provides a clear marker that this element won’t contain content or have a closing tag. There’s no need to look for where the element ends, because it doesn’t, and I find the distinction makes debugging easier.

Accessibility in your inbox

I send an accessibility-centric newsletter on the last day of every month, containing:

  • A roundup of the articles I’ve posted
  • A hot pick from my archives
  • Some interesting posts from around the web

I don’t collect any data on when, where or if people open the emails I send them. Your email will only be used to send you newsletters and will never be passed on. You can unsubscribe at any time.

More posts

Here are a couple more posts for you to enjoy. If that’s not enough, have a look at the full list.

  1. Avatars and alt text

    I really enjoyed Nicolas Steenhout’s recent article on Alt text for avatars or user photos. But there is a context where I would break his rule…

  2. Upgrading from iPhone 13 mini to 16 Pro

    I get a new phone every 3-ish years, give mine to my wife, and now she gives hers to our daughter. I got a 16 Pro this year! Here’s the skinny.