HTML Elements

HTML elements are the building blocks of every page. An element usually consists of a start tag, some content and an end tag, for example <p>Hello</p>. The tags tell the browser what kind of content sits between them.

Anatomy of an Element

  • Start tag: <p>
  • Content: Hello
  • End tag: </p> (note the forward slash)
  • Element: the whole thing, from <p> to </p>

Nested HTML Elements

Elements can contain other elements. Always close inner elements before outer ones, like boxes inside boxes.

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Nesting</title></head>
<body>
  <p>This sentence has <strong>bold text</strong> and <em>italic text</em> inside it.</p>
  <!-- Wrong: <p><strong>text</p></strong> -->
</body>
</html>

Empty (Void) Elements

Some elements have no content and no end tag. Common ones are <br> (line break), <hr> (thematic break), <img>, <input>, <meta> and <link>. Writing <br /> with a slash is also allowed but not required in HTML5.

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Void Elements</title></head>
<body>
  <p>Line one<br>Line two</p>
  <hr>
  <p>Text after a horizontal rule.</p>
</body>
</html>

Block vs Inline Elements

Block elements such as <div>, <p>, <h1> and <ul> start on a new line and take the full width available. Inline elements such as <span>, <a>, <strong> and <img> sit inside a line of text and only take as much width as they need.

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Block vs Inline</title>
<style>div{background:#dbeafe;margin:4px 0}span{background:#fde68a}</style></head>
<body>
  <div>I am a block div.</div>
  <div>I am another block div.</div>
  <p>Inline <span>span one</span> and <span>span two</span> stay on the same line.</p>
</body>
</html>

Never Skip the End Tag

Browsers will often guess where a missing end tag belongs, but the guess can be wrong and lead to strange layouts. Closing every non-void element keeps your HTML predictable and easy to debug.

Frequently asked questions

What is the difference between an HTML tag and an HTML element?

A tag is the markup itself, like <p> or </p>. An element is the complete unit: start tag, content and end tag together.

What are self-closing tags in HTML?

They are void elements such as <img>, <br> and <input> that cannot have content, so they have no end tag. The trailing slash is optional in HTML5.

Is div a block or inline element?

A <div> is a block element. Its inline counterpart for grouping text is <span>.