Attributes

Attributes add extra information to an element: where a link goes, which image to show, how a form field behaves. They're written inside the opening tag as name="value" pairs, and some apply to every element.

Attribute syntax

HTML syntax.html
<a href="https://example.com" title="Visit the example site">Example</a>
  • Attributes go in the opening tag, after the element name, separated by spaces.
  • The value goes in quotes. Double quotes are conventional; single quotes also work.
  • Attribute order doesn't matter.
  • Names are case-insensitive but written in lowercase by convention.

Common attributes by element

Try it yourself
Result
AttributeUsed onPurpose
href<a>, <link>Destination URL
src<img>, <script>, <video>, <iframe>Source file
alt<img>Text alternative for images
width, heightImages, video, canvasIntrinsic size in pixels
type, name, value, placeholderForm controlsField behaviour and data

Global attributes

These can be used on any element:

AttributePurpose
idA unique identifier for one element on the page (lesson 23)
classOne or more space-separated class names for styling and scripting
styleInline CSS (use sparingly — lesson 36)
titleExtra advisory text, often shown as a tooltip
langLanguage of the element's content
hiddenHides the element
tabindexControls keyboard focus order
data-*Custom data for scripts
contenteditable, draggable, translate, dirEditing, drag and drop, translation, text direction
Try it yourself
Result

Boolean attributes

Some attributes are on or off. Their presence alone means "true" — the value doesn't matter:

Try it yourself
Result

Writing disabled="false" does not enable the element — the attribute is still present. To turn a boolean attribute off, remove it entirely.

Custom data attributes

Any attribute starting with data- is valid and reserved for your own use. Scripts read them via the dataset property:

HTML data.html
<button type="button" data-product-id="482" data-price="19.99">Add to cart</button>

In JavaScript, button.dataset.productId is "482". CSS can target them too: [data-price]. They're perfect for attaching IDs and settings to elements without inventing non-standard attributes.

Quoting rules

Quotes are technically optional when a value has no spaces or special characters, but always quoting avoids bugs:

HTML quotes.html
<img src="photo.jpg" alt="My dog">
<p title='He said "woof"'>Use single quotes when the value contains double quotes.</p>
<p title="He said &quot;woof&quot;">Or escape them with &amp;quot;.</p>

Try it yourself

Experiment: change the link's href, add a title, or remove the disabled attribute from the button.

Try it yourself
Result