Explain Codes LogoExplain Codes Logo

Do you need to close meta and link tags in HTML?

html
self-closing-tags
html5
xhtml
Anton ShumikhinbyAnton Shumikhin·Dec 9, 2024
TLDR

In HTML5, closing meta and link tags is not required; they can be self-closed. As in:

<!-- No need to break a sweat --> <meta charset="utf-8"> <link rel="stylesheet" href="my_styles_because_I_have_great_taste_in_design.css">

For XHTML, make sure to add a slash before the tag ends:

<!-- More slashes than a horror movie --> <meta charset="utf-8" /> <link rel="stylesheet" href="xhtml_styles_even_my_mom_likes.css" />

The deciding doctype

The doctype declaration, the bouncer at the beginning of your HTML party, decides who gets in and who doesn't. Depending on its rules, your choice of self-closing or not comes into play:

  • <!DOCTYPE html> - HTML5 doctype where meta and link tags don't need to chew mint before leaving your markup.
  • An XHTML doctype like <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" requires the XML syntax. In other words, every tag including meta and link need to say a proper goodbye like well-bred HTML elements.

Decoding content types

Are you serving tea or coffee? Here's what you need to know about content types and closing tags:

  • Serving content as text/html? You're dealing with HTML parsing rules and self-closing slashes are optional.
  • Serving as application/xhtml+xml? You're in XHTML land. Don't forget to close those tags or risk the horror a broken website.

Quick sand and life buoys

There are some common pitfalls and here's how you can navigate around them:

  • Forget a closing tag in XHTML and you have the equivalent of a zombie apocalypse; your page might not render.
  • Use unnecessary slashes in HTML5 and your code will look like a prickly rose bush; harmless but clustered.
  • When in doubt, use a markup validation service like the W3C Markup Validation. It's like your friendly neighborhood Spiderman!

This isn't a slashing spree

Self-closing slashes don't have to be everywhere in HTML5. Like that eye-widening plot twist in your favorite TV show, they originated from XHTML and are optional in HTML. Here's when they can take the spotlight:

  • Working on an XHTML compatible project? Insert those self-closing slashes.
  • Want a streamlined syntax for an html5-only project? Feel free to omit the slashes, nobody's judging.
  • Whether you say "tomato" or "tomahto", stick to one for consistency's sake.

From novice to superhero

Here are some powerful features of these tags you might overlook:

  • The meta tag can be your guide dog for SEO and browser behavior.
  • The link tag isn't just a pretty face for style sheets. It has capabilities such as defining favicons, preloading resources, and linking alternate languages or content types.