Elements and attributes

HTML · Essentials · 8 min

Every other HTML lesson is just a new element or attribute applied with these rules.

An element usually has an opening tag, content and a closing tag: <p>Some text</p>. Elements nest like boxes, and they must close in reverse order: <p><em>hi</em></p> is right, <p><em>hi</p></em> is not.

Some elements are void: they can't have content and have no closing tag. The common ones are <img>, <br>, <hr>, <input>, <meta> and <link>. You may write <br/>, but in HTML the slash is optional and ignored.

Attributes go inside the opening tag as name="value" pairs and configure the element: <a href="/about">, <img src="cat.jpg" alt="A cat">. Quote values (double quotes are the convention). Boolean attributes are true by being present: <input disabled> is disabled, and disabled="false" is still disabled.

A few global attributes work on any element:

  • id gives a unique name, used by links, labels, CSS and JavaScript.
  • class holds space-separated names for styling groups of elements.
  • hidden hides the element; title adds a tooltip; lang overrides the language.
  • data-* attributes such as data-user-id="42" store your own data for scripts.

Tag and attribute names are case-insensitive, but lowercase is the universal convention. To show a literal < or & in text, use the named character references lt and amp, each written with a leading & and a trailing ;.

Example

<p class="intro" id="top">
  Text with <strong>strong importance</strong> and <em>emphasis</em>.
</p>

<!-- void elements: no closing tag -->
<img src="logo.png" alt="Company logo" width="120" height="40">
<br>

<!-- boolean attribute: present means true -->
<button type="button" disabled>Can't click me</button>

<!-- custom data for scripts: element.dataset.userId === "42" -->
<li data-user-id="42">Ada</li>

Remember

  • Elements nest and must close in reverse order
  • Void elements like <img> and <input> have no closing tag
  • Boolean attributes are on when present, whatever their value
  • id is unique per page; class can be shared

Watch out for

  • Writing disabled="false" and expecting the control to be enabled.

Check yourself

  1. What does <input disabled="false"> render?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes