Ad – 728Γ—90
🌐 Core Elements

HTML Attributes – The Complete Guide

HTML attributes are name–value pairs that you place inside an element's opening tag to configure its behaviour, appearance, or identity. Some attributes are specific to one element (href on <a>, src on <img>). Others are global attributes that work on any HTML element β€” id, class, style, title, lang, and more.

⏱️ 13 min read🎯 BeginnerπŸ“… Updated 2026

What Are Attributes?

An attribute lives inside the opening tag, separated from the element name and from other attributes by a space. The value is wrapped in double quotes.

HTML
<!-- Syntax: element name, then space, then name="value" -->
<a href="https://ylearner.org" target="_blank">ylearner</a>
<!--  ^ element   ^ attribute 1              ^ attribute 2  -->

<img src="/assets/logo.png" alt="ylearner logo" width="120">

<input type="email" id="email" name="email" required placeholder="you@example.com">
Quote style: HTML5 allows single quotes ('), double quotes ("), or even no quotes (if the value has no spaces). Double quotes are the universal convention β€” always use them for consistency and compatibility.

Global Attributes Reference

These attributes can be added to any HTML element:

AttributePurposeExample
idUnique identifier β€” one per pageid="main-nav"
classReusable CSS/JS label(s)class="btn btn-primary"
styleInline CSS stylesstyle="color: red;"
titleTooltip text on hovertitle="Click to expand"
langLanguage of element's contentlang="fr"
dirText direction: ltr or rtldir="rtl"
hiddenHides element (boolean)hidden
tabindexTab order for keyboard navigationtabindex="0"
contenteditableMakes element editable in browsercontenteditable="true"
draggableEnables HTML drag-and-dropdraggable="true"
spellcheckEnable/disable spell checkingspellcheck="false"
translateHint to translation toolstranslate="no"
aria-*ARIA accessibility attributesaria-label="Close"
data-*Custom data storagedata-user-id="42"

The id Attribute

The id attribute assigns a unique identifier to an element. No two elements on the same page should share an id.

Three key uses of id:

  1. Fragment links β€” link directly to a section of the page with href="#section-name"
  2. CSS targeting β€” target with the #id selector
  3. JavaScript β€” retrieve with document.getElementById('id')
HTML
<!-- Fragment link: clicking this jumps to the section below -->
<a href="#about">Jump to About section</a>

<!-- Target section with id -->
<section id="about">
  <h2>About ylearner</h2>
  <p>Free coding tutorials for everyone.</p>
</section>

<!-- CSS targeting -->
<style>
  #about { background: #f0f4ff; padding: 2rem; }
</style>

<!-- JavaScript targeting -->
<script>
  const about = document.getElementById('about');
  about.style.border = '2px solid blue';
</script>

The class Attribute

The class attribute assigns one or more reusable labels to an element. Multiple elements can share the same class, and a single element can have multiple classes (space-separated).

HTML
<!-- Multiple classes on one element -->
<button class="btn btn-primary btn-large">Start Learning</button>

<!-- Multiple elements sharing the same class -->
<div class="card">Card 1</div>
<div class="card">Card 2</div>
<div class="card card--featured">Featured Card</div>

<!-- CSS targeting all cards -->
<style>
  .card { border: 1px solid #dee2e6; padding: 1rem; border-radius: 8px; }
  .card--featured { border-color: #0d6efd; }
</style>

<!-- JavaScript targeting all cards -->
<script>
  document.querySelectorAll('.card').forEach(card => {
    card.addEventListener('click', () => card.classList.toggle('card--active'));
  });
</script>
Ad – 336Γ—280

The style Attribute – Inline CSS

The style attribute applies CSS directly to a single element. Use it sparingly β€” inline styles have very high specificity and are hard to override. They also mix presentation with structure, which makes maintenance harder.

HTML
<!-- Acceptable: one-off dynamic styles set by JavaScript -->
<p id="status" style="color: green; font-weight: bold;">Online</p>

<!-- Better: use a class instead -->
<p id="status" class="status status--online">Online</p>

<!-- Inline styles are fine for email HTML where external CSS won't work -->
<td style="padding: 12px; background-color: #f8f9fa;">Email cell</td>
Avoid overusing inline styles. Prefer CSS classes. Reserve the style attribute for dynamic values set by JavaScript, or for HTML email templates where external stylesheets are unreliable.

The title Attribute

The title attribute adds a tooltip that appears when the user hovers over the element. It's also read by some screen readers.

HTML
<!-- Tooltip on a link -->
<a href="/html/core-elements/tables.html" title="Learn to build data tables in HTML">
  HTML Tables
</a>

<!-- Tooltip on an abbreviation -->
<p>Written in <abbr title="HyperText Markup Language">HTML</abbr>.</p>

<!-- Tooltip on an image -->
<img src="chart.png" alt="Bar chart of course completion rates" title="Data from Jan–June 2026">
Accessibility caveat: The title tooltip is not accessible on touch screens and is not always announced by screen readers. Don't rely on it to convey critical information β€” use visible text or aria-label/aria-describedby for essential content.

Data Attributes – data-*

Custom data attributes let you store extra information on HTML elements without affecting layout or semantics. They follow the pattern data- followed by any name you choose.

HTML
<!-- Store data on elements for JavaScript to read -->
<button class="enroll-btn" data-course-id="html-101" data-price="0">
  Enrol Free
</button>

<ul class="lesson-list">
  <li data-lesson-id="1" data-duration="5">Introduction to HTML</li>
  <li data-lesson-id="2" data-duration="8">HTML Document Structure</li>
  <li data-lesson-id="3" data-duration="10">Block vs Inline Elements</li>
</ul>
JavaScript
// Read data attributes with dataset
const btn = document.querySelector('.enroll-btn');
console.log(btn.dataset.courseId);  // "html-101"
console.log(btn.dataset.price);     // "0"

// dataset uses camelCase for hyphenated attribute names
// data-course-id  β†’  dataset.courseId
// data-lesson-id  β†’  dataset.lessonId

// Iterate over lessons and total their duration
let totalMinutes = 0;
document.querySelectorAll('[data-duration]').forEach(item => {
  totalMinutes += parseInt(item.dataset.duration, 10);
});
console.log(`Total: ${totalMinutes} minutes`); // "Total: 23 minutes"

Boolean Attributes

Some attributes don't need a value β€” their presence alone activates the feature. These are called boolean attributes. The value (if written) must be either the attribute name itself or an empty string.

HTML
<!-- Boolean attributes: presence = true, absence = false -->

<!-- Disable a button -->
<button disabled>Submit</button>

<!-- Pre-check a checkbox -->
<input type="checkbox" checked>

<!-- Mark an input as required -->
<input type="email" required>

<!-- Make an input read-only -->
<input type="text" value="gmostafa1210@gmail.com" readonly>

<!-- Allow multiple file selection -->
<input type="file" multiple>

<!-- Autoplay a video (muted required in most browsers) -->
<video src="intro.mp4" autoplay muted loop></video>

<!-- Hide an element -->
<div hidden>This won't render on screen</div>

<!-- All of these are equivalent for boolean attributes: -->
<input required>
<input required="">
<input required="required">

πŸ“‹ Summary

  • Attributes are name="value" pairs inside opening tags. Always use double quotes around values.
  • Global attributes work on any element: id, class, style, title, lang, dir, hidden, tabindex, contenteditable.
  • id β€” unique per page; used for fragment links, CSS #selector, and getElementById().
  • class β€” reusable; multiple per element; targeted by CSS .selector and querySelectorAll().
  • style β€” inline CSS; use sparingly; prefer external/class-based CSS.
  • data-* β€” custom data storage for JavaScript; accessed via element.dataset.attributeName.
  • Boolean attributes (disabled, checked, required, readonly, hidden) β€” presence alone activates them; no value needed.

Frequently Asked Questions

Are attribute names case-sensitive?

In HTML5 (not XML/XHTML), attribute names are case-insensitive β€” ID, Id, and id are all valid. However, the convention is always lowercase. Attribute values can be case-sensitive depending on the attribute β€” URL values are case-sensitive on case-sensitive servers, and CSS class names in HTML are case-sensitive when referenced from CSS or JavaScript.

Can I create my own custom attributes?

Yes β€” use data-* attributes for custom data. Do not invent arbitrary attribute names like <div myattr="value"> β€” those are non-standard, may cause validation errors, and could conflict with future HTML attributes. Always prefix custom data with data-.

What is the tabindex attribute used for?

tabindex controls whether an element is focusable by keyboard (Tab key) and its position in the tab order. tabindex="0" adds the element to the natural tab order. tabindex="-1" makes it focusable by script only (useful for modal dialogs). Positive values (tabindex="1", tabindex="2", etc.) set an explicit order but are generally discouraged because they override the natural DOM order and are hard to maintain.

Is the style attribute bad practice?

Not categorically β€” it depends on context. For dynamically calculated values in JavaScript, inline styles are perfectly appropriate. For email HTML templates, they are often the only reliable option. For regular web pages, prefer CSS classes for maintainability, separation of concerns, and ease of theming. A good rule of thumb: if the value never changes based on user interaction or data, it belongs in a stylesheet, not an inline style attribute.