HTML Attributes

Beginner
14 min read
Updated: Nov 2026
6 examples
210+ attributes

Definition and Usage

HTML attributes are extra settings you write on an element’s opening tag. They look like name="value" and tell the browser how that element should behave, look (via CSS hooks), or be described.

Tags vs attributes

A tag chooses the element type (<a>, <img>, <input>). Attributes configure that element: href for the link URL, alt for image text, required for a mandatory field.

What do beginners use most?

Master id, class, href, src, alt, type, name, for, and data-* first. Use the A–Z index when you need a specific attribute guide.

Hub vs single-attribute pages

This page teaches how attributes work in HTML. Each name in the index (and in the sidebar) opens a focused guide—start with Global Attributes for properties that apply almost everywhere.

Opening tag only.

Attributes belong on the start tag. Never put them on a closing tag like </p class="x">.

Boolean rule.

For required, disabled, checked, and hidden, presence means true. Omit the attribute to turn it off.

Events are attributes too.

onclick and friends are HTML event attributes—see Basic Events. Prefer addEventListener in larger projects.

HTML Syntax

Attributes sit inside the opening tag, space-separated:

HTML
<!-- name="value" -->
<a href="/html" class="nav-link">HTML tutorial</a>

<!-- boolean: present = true -->
<input type="email" name="email" required>

<!-- multiple classes -->
<p id="intro" class="lead muted">Hello</p>

Core HTML Concepts

How attributes are grouped on real pages:

KindExamplesNotes
Globalid, class, lang, data-*Almost any element — guide
Element-specifichref, src, actionOnly valid on matching tags
Booleanrequired, disabled, checkedPresent = true; omit = false
Event (on*)onclick, onchangeRun script when something happens

Starter attributes by job

JobAttributes
Style / script hooksid, class, style
Linkshref, target, rel
Imagessrc, alt, width, height
Formsaction, method, name, type, required, for
Custom datadata-*

Common patterns

PatternExample
String valueclass="btn primary"
Boolean<input required>
URLhref="/docs" / src="photo.jpg"
Label association<label for="email"> + id="email"

How to Use Attributes in HTML

A practical workflow:

  1. Choose the right tag for the content.
  2. Add only the attributes that tag needs (href on links, alt on informative images).
  3. Quote every value; space-separate multiple classes.
  4. Use id sparingly (unique); use class for reusable styles.
  5. For custom script data, prefer data-* over invented attribute names.
  6. Open an individual attribute page from the A–Z index when you need details.

Live Preview

Toggle the class attribute on the sample paragraph—same idea as writing class="lead" in HTML.

CSS targets .lead and .highlight via the class attribute.

Preview

The class attribute groups elements for CSS.

HTML Examples

Six everyday patterns: class, id + for, images, forms, links, and data-*.

Example 1 — class on paragraphs

HTML
<p class="lead">Intro paragraph with larger text.</p>
<p>Highlight a <span class="highlight">word</span> inline.</p>
Try It Yourself

How It Works

  1. class lists one or more CSS class names.
  2. Spaces separate multiple classes on one element.
  3. CSS selects with .lead and .highlight.
  4. Any tag can carry a class—not only div.

Example 2 — id + label for

HTML
<label for="username">Username</label>
<input type="text" id="username" name="username">
Try It Yourself

How It Works

  1. id must be unique in the page.
  2. for on the label matches that id.
  3. Clicking the label focuses the input.
  4. name is what gets submitted with the form.

Example 3 — img src, alt, width, height

HTML
<img src="logo.png" alt="Site logo"
     width="120" height="60">
Try It Yourself

How It Works

  1. src points to the image file.
  2. alt describes the image for accessibility.
  3. width / height reserve space and reduce layout shift.
  4. Decorative images use alt="".

Example 4 — form action, method, required

HTML
<form action="/subscribe" method="post">
  <label for="email">Email</label>
  <input type="email" id="email" name="email" required>
  <button type="submit">Subscribe</button>
</form>
Try It Yourself

How It Works

  1. action is where the form data is sent.
  2. method="post" puts data in the request body.
  3. required blocks empty submits in the browser.
  4. Still validate on the server.

Example 6 — data-* attributes

HTML
<article data-id="42" data-category="tutorial">
  <h2>HTML Attributes</h2>
  <p>Custom data attributes for scripts.</p>
</article>
Try It Yourself

How It Works

  1. data-* stores custom values safely in HTML.
  2. Scripts read them via element.dataset.
  3. data-user-id becomes dataset.userId.
  4. Prefer this over invented non-standard attributes.

Full A–Z Attribute Index

All 210 attributes in this reference, sorted alphabetically. Open any name for its dedicated guide.

AttributeSummary
acceptFile type filter on input type=file
accept-charsetCharacter encodings accepted by a form submission
accesskeyKeyboard shortcut to focus or activate an element
actionURL that receives form data on submit
alignObsolete horizontal alignment — use CSS instead
altAlternative text for images (accessibility)
archiveLegacy object archive list
asResource type hint for link preload/prefetch
asyncLoad script asynchronously without blocking parse
autocapitalizeMobile keyboard capitalization hint
autocompleteEnable or disable browser autocomplete on inputs
autofocusFocus an element when the page loads
autoplayStart media playback automatically
axisLegacy table axis category
bgcolorObsolete background color — use CSS
borderBorder width on tables (legacy presentation)
cellpaddingLegacy table cell padding
cellspacingLegacy table cell spacing
charLegacy table alignment character
charoffLegacy offset for char alignment
charsetCharacter encoding for the document or script
checkedPre-select checkbox or radio input
citeSource URL for a quotation
classCSS class names for styling and scripting
classidLegacy object class identifier
codebaseLegacy object code base URL
codetypeLegacy object code MIME type
colorObsolete text color — use CSS
colsVisible width of a textarea in columns
colspanNumber of columns a table cell spans
compactLegacy compact list rendering
contentValue of a meta element
contenteditableMake element content user-editable
controlsShow default media player controls
coordsCoordinates for image map hotspots
crossoriginCORS setting for scripts and media
dataMachine-readable value on the data element
data-*Custom data-* attributes for scripts
datetimeMachine-readable date/time value
declareLegacy param declaration flag
defaultDefault track in media elements
deferDefer script execution until HTML is parsed
dirText direction: ltr, rtl, or auto
dirnameSubmit text direction with form fields
disabledDisable user interaction on a control
downloadTreat link as a download of the resource
draggableEnable drag-and-drop on an element
enctypeEncoding type for form submission
forAssociate label with a form control id
formForm id that owns this control
formactionOverride form action URL for a button
formenctypeOverride form enctype for a button
formmethodOverride form method for a button
formnovalidateSkip validation when button submits
formtargetTarget browsing context for button submit
frameLegacy frameset frame definition
frameborderLegacy iframe border display
headersAssociate table cells with header cell ids
heightHeight of an element (often on img, canvas)
hiddenHide element from rendering
highUpper bound for meter element range
hrefHyperlink destination URL
hreflangLanguage of the linked resource
hspaceLegacy horizontal spacing around images
http-equivHTTP header emulation in meta elements
idUnique identifier within the document
integritySubresource integrity hash for scripts/styles
ismapServer-side image map on img inside a link
kindTrack type for video subtitles/captions
labelVisible caption for optgroup or track
langLanguage of element content (BCP 47)
languageLegacy script language hint
listDatalist id for input suggestions
longdescLegacy long description link for images
loopRepeat media playback
lowLower bound for meter element range
manifestWeb app manifest URL
marginheightLegacy iframe margin height
marginwidthLegacy iframe margin width
maxMaximum value for numeric/date inputs
maxlengthMaximum character length for text inputs
mediaMedia query for link, style, or source
methodHTTP method for form submission (get/post)
minMinimum value for numeric/date inputs
minlengthMinimum character length for text inputs
multipleAllow multiple values or file selection
mutedMute audio/video by default
nameName submitted with form controls
nohrefLegacy area without hyperlink
nomoduleSkip script on browsers that support modules
nonceCSP nonce for inline script/style
novalidateDisable native form validation
onabortInline JavaScript handler for the abort event (global).
onafterprintInline JavaScript handler for the afterprint event (global).
onbeforeprintInline JavaScript handler for the beforeprint event (global).
onbeforeunloadInline JavaScript handler for the beforeunload event (global).
onblurInline JavaScript handler for the blur event (global).
oncanplayInline JavaScript handler for the canplay event (global).
oncanplaythroughInline JavaScript handler for the canplaythrough event (global).
onchangeInline JavaScript handler for the change event (global).
onclickInline JavaScript handler for the click event (global).
oncontextmenuInline JavaScript handler for the contextmenu event (global).
oncopyInline JavaScript handler for the copy event (global).
oncuechangeInline JavaScript handler for the cuechange event (global).
oncutInline JavaScript handler for the cut event (global).
ondblclickInline JavaScript handler for the dblclick event (global).
ondragInline JavaScript handler for the drag event (global).
ondragendInline JavaScript handler for the dragend event (global).
ondragenterInline JavaScript handler for the dragenter event (global).
ondragleaveInline JavaScript handler for the dragleave event (global).
ondragoverInline JavaScript handler for the dragover event (global).
ondragstartInline JavaScript handler for the dragstart event (global).
ondropInline JavaScript handler for the drop event (global).
ondurationchangeInline JavaScript handler for the durationchange event (global).
onemptiedInline JavaScript handler for the emptied event (global).
onendedInline JavaScript handler for the ended event (global).
onerrorInline JavaScript handler for the error event (global).
onfocusInline JavaScript handler for the focus event (global).
onhashchangeInline JavaScript handler for the hashchange event (global).
oninputInline JavaScript handler for the input event (global).
oninvalidInline JavaScript handler for the invalid event (global).
onkeydownInline JavaScript handler for the keydown event (global).
onkeypressInline JavaScript handler for the keypress event (global).
onkeyupInline JavaScript handler for the keyup event (global).
onloadInline JavaScript handler for the load event (global).
onloadeddataInline JavaScript handler for the loadeddata event (global).
onloadedmetadataInline JavaScript handler for the loadedmetadata event (global).
onloadstartInline JavaScript handler for the loadstart event (global).
onmousedownInline JavaScript handler for the mousedown event (global).
onmousemoveInline JavaScript handler for the mousemove event (global).
onmouseoutInline JavaScript handler for the mouseout event (global).
onmouseoverInline JavaScript handler for the mouseover event (global).
onmouseupInline JavaScript handler for the mouseup event (global).
onmousewheelInline JavaScript handler for the mousewheel event (global).
onofflineInline JavaScript handler for the offline event (global).
ononlineInline JavaScript handler for the online event (global).
onpagehideInline JavaScript handler for the pagehide event (global).
onpageshowInline JavaScript handler for the pageshow event (global).
onpasteInline JavaScript handler for the paste event (global).
onpauseInline JavaScript handler for the pause event (global).
onplayInline JavaScript handler for the play event (global).
onplayingInline JavaScript handler for the playing event (global).
onpopstateInline JavaScript handler for the popstate event (global).
onprogressInline JavaScript handler for the progress event (global).
onratechangeInline JavaScript handler for the ratechange event (global).
onresetInline JavaScript handler for the reset event (global).
onresizeInline JavaScript handler for the resize event (global).
onscrollInline JavaScript handler for the scroll event (global).
onsearchInline JavaScript handler for the search event (global).
onseekedInline JavaScript handler for the seeked event (global).
onseekingInline JavaScript handler for the seeking event (global).
onselectInline JavaScript handler for the select event (global).
onstalledInline JavaScript handler for the stalled event (global).
onstorageInline JavaScript handler for the storage event (global).
onsubmitInline JavaScript handler for the submit event (global).
onsuspendInline JavaScript handler for the suspend event (global).
ontimeupdateInline JavaScript handler for the timeupdate event (global).
ontoggleInline JavaScript handler for the toggle event (global).
onunloadInline JavaScript handler for the unload event (global).
onvolumechangeInline JavaScript handler for the volumechange event (global).
onwaitingInline JavaScript handler for the waiting event (global).
onwheelInline JavaScript handler for the wheel event (global).
openOpen details/summary or dialog by default
optimumSuggested value for meter element
patternRegex pattern for input validation
placeholderHint text shown in empty inputs
posterPoster image before video plays
preloadHint how much media to buffer
readonlyDisplay value but prevent editing
referrerpolicyReferrer header policy for requests
relRelationship of linked resource to document
requiredRequire field before form submit
revLegacy reverse link relationship
reversedReverse numbering on ordered lists
rowsVisible height of textarea in rows
rowspanNumber of rows a table cell spans
rulesLegacy table border rules
sandboxSecurity restrictions on iframe content
schemeObsolete meta scheme (deprecated)
scopeHeader cell scope in tables (row/col)
scrollingLegacy iframe scrollbars setting
selectedPre-select option in select element
shapeHotspot shape in image maps
sizeVisible size of select or text input
sizesResponsive image sizes for srcset
spellcheckEnable browser spell checking
srcURL of embedded resource (img, script, etc.)
srcdocInline HTML document for iframe
srclangLanguage of track element text
srcsetResponsive image candidates for img/source
standbyLegacy object standby message
startStarting number for ordered lists
stepStep interval for numeric inputs
styleInline CSS declarations
summaryLegacy table summary (use caption instead)
tabindexKeyboard focus order
targetBrowsing context for link/form submit
titleAdvisory tooltip text
translateHint whether content should be translated
typeInput type or MIME type of resource
typemustmatchRequire exact MIME for object
usemapClient-side image map reference
valignLegacy vertical alignment — use CSS
valueCurrent or default value of a control
valuetypeLegacy param value type
versionLegacy HTML version on html element
vspaceLegacy vertical spacing around images
widthWidth of an element
wrapWhether textarea text wraps on submit
xmlnsXML namespace declaration

Edge Cases & Pitfalls

Most attribute mistakes are wrong tags, missing quotes, or misused booleans.

bool

disabled="false"

The attribute is still present, so the control stays disabled. Omit it to enable the control.

id

Duplicate id values

Each id must be unique. Duplicates break labels, fragment links, and getElementById.

scope

Wrong attribute on a tag

href belongs on links (and a few others), not on a plain div. Check the tag’s allowed attributes.

a11y

Missing alt on images

Informative images need meaningful alt. Decorative images should use alt="".

legacy

Presentational attributes

Prefer CSS over obsolete attrs like bgcolor, align, and font color.

blank

target="_blank" alone

Add rel="noopener noreferrer" so the new page cannot access your window.

Browser Support

Core HTML attributes—id, class, href, src, alt, type, name, and boolean form attributes—are Baseline HTML. Modern helpers like data-* and srcset work in all current browsers.

✓ Baseline · Widely available

HTML attributes

Standard attributes are among the most stable parts of the web platform.

100% core attributes
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
HTML attributes Universal

Bottom line: Quote values, use the right attributes on the right tags, and lean on id/class/href/src/alt/name first.

Key Takeaways

  • Attributes are name="value" pairs on opening tags.
  • Global vs specific: id/class almost anywhere; href on links.
  • Booleans are on/off by presence—never ="false".
  • Next: Global Attributes or the A–Z index above.

One line: Attributes configure HTML elements—quote values, pick the right ones for each tag, start with id/class/href/src/alt.

Frequently Asked Questions

Attributes are name="value" pairs written inside an element's opening tag. They configure the element—href on a link, alt on an image, class for CSS, required on a form field.
A tag names the element (p, a, img). Attributes add properties to that element. Tags build structure; attributes configure behavior, identity, and accessibility.
Global attributes work on almost any element—id, class, lang, dir, title, hidden, tabindex, data-*, and many on* event attributes. See the Global Attributes guide for the full set.
Boolean attributes are true when present and false when absent. Examples: required, disabled, checked, hidden. Omit the attribute to turn it off—do not use ="false".
Always quote values with double quotes in tutorials and production HTML: class="card". Unquoted values are fragile and harder to read.
Start with id, class, href, src, alt, type, name, for, required, and data-*. Then open the A–Z index when you need a specific attribute.

Practice in the editor

Try class, forms, links, images, and data-* attributes live.

Open Try It editor →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful