As you learned in Part 1 of this series, an HTML tag specifies the meaning of some content. Oftentimes though, the tag itself does not provide enough information, so HTML tags have what are called attributes, which can be seen as a way of specifying configuration options for that tag.

Shape of an attribute

An attribute consists of a name and value pair, separated by an equals sign. The value must also be contained in quotes (double or single) :

name="value"
name='value'

Attributes appear within the start/opening tag right after the tag name, and multiple attributes are separated with a space. The order of the attributes makes no difference :

Types of attributes

There are 3 different kinds of attributes:

Standard attributes

These attributes are supported by almost all HTML tags. The most common are class, id and title

Event attributes

These attributes are for specifying actions that should be performed when certain events take place in a browser, such as the onclick attribute. But once you’ve learned about the concept of separation of concerns, you’ll know to stay away from these attributes – it’s better to handle events with Javascript.

Element-specific attributes

These attributes are specific to certain elements, so you’ll use them often in your coding! An example of such an attribute is the action attribute for a <form> tag.

Optional or Required

Though most attributes are optional, there are some tags which require certain attributes. An <img> tag, for example, wouldn’t mean much if you didn’t specify which image should be placed there! You specify the source of the image with the src attribute, and the value of the src attribute is the location of the image. HTML is very logical! For accessibility reasons, the <img> tag also requires an alt attribute, which specifies some text to display on the page if the image couldn’t be loaded. So a minimal image tag looks like this :

<img src="path/to/image" alt="Some descriptive text" />

which is enough to include an image into your page, like this :

Reference

A great reference for HTML tags, that displays their properties such as their allowed attributes and values, is w3schools.com. On the page about the <img> tag, for instance, you can see that the src and alt attributes are both required.

That’s about all you need to know about attributes, and you’re now ready to build a complete HTML page, which you’ll be doing in the next article!