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 elementclass - Specifies one or more class names for an elementstyle - Specifies inline CSS stylestitle - 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 elementplaceholder - Specifies a short hint that describes the expected valuerequired - Specifies that an input field must be filled outsrc - Specifies the source file path for images, videos, etc.alt - Specifies alternative text for imageswidth and height - Specify dimensionscontrols - Specifies that audio/video controls should be displayedBoolean Attributes
Some attributes don't need a value - their presence alone indicates "true":
<input type="checkbox" checked> <button disabled>Can'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 elementaria-hidden - Indicates whether the element is exposed to screen readersaria-live - Indicates that an element will be updated dynamicallyExample
<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:
- A text input with placeholder and required attributes
- An email input with pattern validation
- A disabled submit button
- A checkbox with custom data attributes
<form> <!-- Your solution here --> </form>