Free HTML tutorial

HTML Attributes: Add Information to Elements

Learn HTML attribute syntax with examples of href, src, alt, id, class and boolean attributes.

Write an attribute

Attributes provide additional information about an element. They are written in the opening tag as a name and, for many attributes, a value.

<a href="https://example.com/">Visit the example site</a>

Quote attribute values, especially when they contain spaces. Quoted values are consistent and easy to read.

Common attributes

  • href gives a link its destination.
  • src identifies a resource such as an image file.
  • alt provides alternative text for an image. Use an empty value for decorative images.
  • id gives an element a unique identifier in the document.
  • class assigns one or more reusable class names.
<img src="images/flower.jpg" alt="Pink flower in a garden">
<button type="button" disabled>Unavailable</button>

Boolean attributes

A boolean attribute is true when it is present. For example, adding disabled disables a form control; leaving it out means the control is not disabled by that attribute.

<input type="email" required>
<button type="button" disabled>Unavailable</button>

For a boolean attribute, presence is what matters. Writing disabled="false" still leaves the attribute present, so the control remains disabled. Remove the attribute when you want the control enabled.

Global and element-specific attributes

Global attributes such as id, class, lang and title can be used on most HTML elements. Other attributes belong to particular elements: href is used on links, while src and alt are used on images. An attribute only works as intended when the element supports it.

Use classes, IDs and custom data

An element can have several class names separated by spaces. Use classes for styles or groups of elements. An id should identify one element on the page and can also be used as a link destination. Custom data-* attributes can store small values for scripts to read through an element's dataset.

<button class="button button-primary" id="save-button"
        data-action="save">Save</button>

<script>
  const button = document.querySelector("#save-button");
  console.log(button.dataset.action); // "save"
</script>

Do not put private information in a data-* attribute: it is visible in the page source and browser tools. Keep CSS classes and IDs descriptive so the purpose of the markup is easy to understand.

Attributes have element-specific rules. Check that an attribute is supported on the element where you use it.

For a full reference, see MDN's HTML global attributes documentation.

Practice: Try an attribute example in the online HTML and CSS editor and preview the result.