HTML Attributes Tutorial

Attributes provide additional information about HTML elements and modify their behavior.

What Are HTML Attributes?

HTML attributes are special words used inside the opening tag to control the element's behavior. They provide additional information about elements.

  • All HTML elements can have attributes
  • Attributes usually come in name/value pairs like: name="value"
  • Attributes are always specified in the start tag

Basic Attribute Syntax

Here's the basic syntax for using attributes:

<tagname attribute="value">Content</tagname>
Example
<a href="https://example.com" target="_blank">Visit Example</a>

This link has two attributes: href and target

Common HTML Attributes

id - Specifies a unique id for an element
class - Specifies one or more class names for an element
style - Specifies inline CSS styles
title - Specifies extra information about an element (shown as tooltip)

type - Specifies the type of input element (text, password, checkbox, etc.)
value - Specifies the value of an input element
placeholder - Specifies a short hint that describes the expected value
required - Specifies that an input field must be filled out

src - Specifies the source file path for images, videos, etc.
alt - Specifies alternative text for images
width and height - Specify dimensions
controls - Specifies that audio/video controls should be displayed

Boolean Attributes

Some attributes don't need a value - their presence alone indicates "true":

<input type="checkbox" checked>
<button disabled>Can&apos;t Click Me</button>
<video controls>
In XHTML, boolean attributes must have values (e.g., checked="checked"), but in HTML5 this is optional.

Custom Data Attributes

HTML5 allows custom attributes prefixed with data-:

<div id="user" data-user-id="1234" data-role="admin">
  User Information
</div>

These can be accessed via JavaScript:

const user = document.getElementById('user');
console.log(user.dataset.userId); // "1234"

ARIA Attributes

Accessibility attributes that improve screen reader support:

aria-label - Defines a string that labels the current element
aria-hidden - Indicates whether the element is exposed to screen readers
aria-live - Indicates that an element will be updated dynamically
Example
<button aria-label="Close" onclick="closeDialog()">X</button>

Provides context for screen readers when the visual label is minimal

Practice Exercise

Attribute Challenge

Create a form with:

  1. A text input with placeholder and required attributes
  2. An email input with pattern validation
  3. A disabled submit button
  4. A checkbox with custom data attributes
<form>
  <!-- Your solution here -->
</form>