HTML Attributes

  • All HTML elements can have attributes.
  • Attributes provide additional information about elements.
  • Attributes are always specified in the start tag.
  • They usually come in name/value pairs like name="value".

The href and src Attributes

Example

The <a> tag uses href for the address to link to; <img> uses src for the image file:

<!DOCTYPE html>
<html>
<head>
  <title>Page Title</title>
</head>
<body>

<a href="https://www.wikipedia.org">Visit Wikipedia</a>
<br><br>
<img src="https://picsum.photos/id/1015/240/120" alt="A river between mountains" width="240" height="120">

</body>
</html>

Result

width, height, alt, style, lang, title

AttributeUsed onPurpose
alt<img>text shown if the image cannot load, and read by screen readers
width, height<img>, <video>size in pixels; reserves space so the page does not jump
styleany elementinline CSS: style="color:red;"
lang<html>language of the page: lang="en", lang="hi"
titleany elementextra information shown as a tooltip on hover
id, classany elementnames used by CSS and JavaScript

Example

Hover over the paragraph to see its title:

<!DOCTYPE html>
<html>
<head>
  <title>Page Title</title>
</head>
<body>

<p title="I am a tooltip" style="color:teal;">Hover over me.</p>

</body>
</html>

Result

Quote Attribute Values

Always put attribute values in quotes. Double quotes are the most common; use single quotes when the value itself contains double quotes:

<p title='John "ShotGun" Nelson'>Quotes inside quotes</p>

Exercise

Exercise: Add an image of size 300×200 with the file name logo.png and the alternate text "Company logo".

Show answer
<img src="logo.png" alt="Company logo" width="300" height="200">