0
0
HTMLmarkup~5 mins

Self-closing tags in HTML

Choose your learning style9 modes available
Introduction

Self-closing tags let you write HTML elements that don't need a separate closing tag. They keep your code neat and simple.

When adding images to a webpage using the <img> tag.
When inserting a line break with the <br> tag.
When adding a horizontal line using the <hr> tag.
When including meta information in the <meta> tag inside the <head>.
When linking to external stylesheets with the <link> tag.
Syntax
HTML
<tag-name />
Self-closing tags end with a slash before the closing angle bracket.
In HTML5, the slash is optional but allowed for compatibility.
Examples
An image tag that shows a picture. It doesn't need a closing tag.
HTML
<img src="photo.jpg" alt="A photo" />
A line break tag that moves text to the next line.
HTML
<br />
A horizontal line to separate content visually.
HTML
<hr />
Defines the character encoding of the webpage.
HTML
<meta charset="UTF-8" />
Sample Program

This webpage uses several self-closing tags: <meta>, <link>, <br>, <img>, and <hr>. They don't need separate closing tags, making the code cleaner.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Self-closing Tags Example</title>
  <link rel="stylesheet" href="styles.css" />
</head>
<body>
  <h1>Welcome to Self-closing Tags</h1>
  <p>This is a paragraph.<br />Here is a line break.</p>
  <img src="https://via.placeholder.com/150" alt="Placeholder Image" />
  <hr />
  <p>End of example.</p>
</body>
</html>
OutputSuccess
Important Notes

In HTML5, self-closing tags like <br> and <img> do not require the slash (/), but including it is allowed for compatibility.

Always include the alt attribute in <img> tags for accessibility.

Self-closing tags cannot have any content inside them.

Summary

Self-closing tags simplify HTML by not needing a separate closing tag.

Common self-closing tags include <img>, <br>, <hr>, <meta>, and <link>.

Using self-closing tags keeps your code clean and easier to read.