HTML Attributes

HTML attributes give extra information about an element. They are always written in the start tag as name="value" pairs, for example <a href="https://example.com">. An element can have several attributes separated by spaces.

Common HTML Attributes

  • href: the destination of a link
  • src: the source file of an image, script, audio or video
  • alt: alternative text for an image
  • width and height: dimensions of images and media
  • id: a unique name for one element on the page
  • class: one or more group names used by CSS and JavaScript
  • style: inline CSS for a single element
  • title: extra info shown as a tooltip on hover
  • lang: the language of the content

href and src Example

Hover over the link to see the title tooltip. If the image fails to load, the alt text is shown instead and is read aloud by screen readers.

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Attributes</title></head>
<body>
  <a href="https://www.wikipedia.org" title="Opens Wikipedia">Visit Wikipedia</a>
  <p><img src="https://picsum.photos/id/1015/240/160" alt="River in a valley" width="240" height="160"></p>
</body>
</html>

id and class Attributes

Use id for one unique element and class for groups of elements that share styling.

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>id and class</title>
<style>
  #main-title { color: #1d4ed8; }
  .note { background: #fef9c3; padding: 6px; }
</style></head>
<body>
  <h1 id="main-title">Shopping Notes</h1>
  <p class="note">Buy rice and tea.</p>
  <p class="note">Return library books.</p>
</body>
</html>

Boolean Attributes

Some attributes need no value; their presence alone turns them on. Examples are disabled, checked, required, readonly and hidden.

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Boolean Attributes</title></head>
<body>
  <input type="text" value="Can't edit me" disabled>
  <label><input type="checkbox" checked> Subscribed</label>
  <p hidden>You will not see this paragraph.</p>
</body>
</html>

Quoting Attribute Values

HTML allows unquoted values without spaces, but always use double quotes to be safe. If the value itself contains double quotes, wrap it in single quotes instead: title='He said "hi"'. Attribute names should be lowercase.

Frequently asked questions

What is the difference between id and class in HTML?

An id must be unique on the page and identifies one element. A class can be reused on many elements and an element can have several classes.

Why is the alt attribute important?

alt text describes the image for screen reader users, appears when the image fails to load, and helps search engines understand the image.

Can I create my own HTML attributes?

Yes, using data-* attributes such as data-user-id="42". They are valid HTML and easy to read from JavaScript via element.dataset.