HTML Attributes

HTML attributes provide additional information about HTML elements. They are always specified in the opening tag and usually come in name/value pairs like name="value".

Attribute Syntax

Attributes are added to the opening tag of an element:

<element attribute="value">Content</element>

Multiple attributes can be added:

<element attribute1="value1" attribute2="value2">Content</element>

Global Attributes

Global attributes can be used on any HTML element:

Common Element-Specific Attributes

Links (<a>)

<a href="https://example.com" target="_blank" rel="noopener">Visit Example</a>

Images (<img>)

<img src="image.jpg" alt="A beautiful landscape" width="300" height="200" loading="lazy">

Forms (<form>)

<form action="/submit" method="POST" enctype="multipart/form-data">

Input Fields (<input>)

<input type="email" name="user_email" placeholder="Enter your email" required>

Buttons (<button>)

<button type="submit" disabled>Submit Form</button>

Select Elements (<select>)

<select name="country" multiple size="3">
  <option value="us">United States</option>
  <option value="ca">Canada</option>
</select>

Textarea (<textarea>)

<textarea name="message" rows="4" cols="50" placeholder="Enter your message" maxlength="500"></textarea>

Boolean Attributes

Some attributes are boolean - they don't need a value. Their presence indicates true, absence indicates false:

<input type="checkbox" checked>
<input type="text" disabled>

Custom Data Attributes

HTML5 allows custom data attributes using the data- prefix:

<div data-user-id="123" data-role="admin">User Info</div>

These can be accessed in JavaScript using element.dataset.userId.

Best Practices

  1. Always use lowercase for attribute names
  2. Always quote attribute values
  3. Use meaningful id and class names
  4. Provide alt text for images
  5. Use semantic attributes appropriately
  6. Avoid inline styles when possible (prefer CSS classes)

Accessibility Considerations

Loading