Attributes give an element extra information. They always go in the opening tag and usually come as a name and a value.
<a href="https://example.com" title="A sample website">Visit the example</a>
The a element is a link. It has two attributes:
hrefis the address the link goes to.titleis extra text some browsers show when you hover.
The syntax
<element name="value" another-name="another value">content</element>
- Put a space between the tag name and each attribute.
- Use
=between the name and the value. - Put the value in quotes. Double quotes are the usual choice.
Attributes you will see a lot
| Attribute | Used on | Meaning |
|---|---|---|
href | a | The address a link opens |
src | img, script | The file to load |
alt | img | A text description of the image |
width, height | img | Size in pixels |
lang | html and others | The language of the content |
id, class | most elements | Names for CSS and JavaScript |
Attributes without a value
Some attributes are switches. If they are present, they are on.
<input type="checkbox" checked>
<button disabled>Not available yet</button>
Quotes and special characters
If a value contains double quotes, wrap it in single quotes, or use ". Keep it simple and avoid quotes inside values where you can.
Missing quotes around values with spaces
<img alt=Red front door> is read as an alt of “Red” plus two stray attributes. Always quote values: alt="Red front door".Lowercase names
Exercise: add attributes
Write a link to https://example.org with the text “Read more” that has a title of “Opens the example site”.
Show a possible solution
<a href="https://example.org" title="Opens the example site">Read more</a>