HTML Attributes in Your Code

By Nikhil Abraham

Attributes provide additional ways to modify the behavior of an element or specify additional information. Usually, but not always, you set an attribute equal to a value enclosed in quotes. Here’s an example using the title attribute and the hidden attribute:

<h1 title="United States of America">USA</h1>
<h1 hidden>New York City</h1>

The title attribute provides advisory information about the element that appears when the mouse cursor hovers over the affected text (in other words, a tooltip). In this example, the word USA is styled as a header using the <h1> tag with a title attribute set equal to “United States of America”. In a browser, then, when you place your mouse cursor over the word USA, the text United States of America displays as a tooltip.

image0.jpg

The hidden attribute indicates that the element is not relevant, so the browser won’t render any elements with this attribute. In this example, the words New York City never appear in the browser window because the hidden attribute is in the opening <h1> tag. More practically, hidden attributes are often used to hide fields from users so they can’t edit them. For example, an RSVP website may want to include but hide from user view a date and time field.

The hidden attribute is new in HTML5, which means it may not work on some older browsers.

You don’t have to use one attribute at a time. You can include multiple attributes in the opening HTML tag, like this:

<h1 title="United States of America" lang="en">USA</h1>

In this example, the title attribute is used, and the lang attribute, setting it equal to “en” to specify that the content of the element is in the English language.

When including multiple attributes, separate each attribute with one space.

Keep the following rules in mind when using attributes:

  • If using an attribute, always include the attribute in the opening HTML tag.

  • Multiple attributes can modify a single element.

  • If the attribute has a value, then use the equal sign (=) and enclose the value in quotes.