HTML Elements and Attributes: id, class, title, href
Elements are the building blocks of a page, and attributes configure them. An attribute is written inside the opening tag as name="value": in <a href="https://www.sqlite.org/">, the attribute href tells the link where to go.
Nesting
Elements can contain other elements. In <p>A paragraph is an <em>element</em>.</p>, the em element sits inside the paragraph. Close inner elements before outer ones; <p><em>text</p></em> is invalid, and browsers will repair it in ways you may not expect.
Void elements
Some elements have no content and therefore no closing tag. These void elements include <br> (line break), <img> (image), <input>, <meta>, <link> and <hr>. You may see them written as <br /> in older code; in HTML the slash is allowed but has no effect.
Common attributes
Some attributes work on almost every element. These global attributes include:
id: a unique name for one element on the page, used by links like#intro, by CSS and by JavaScript.class: one or more space-separated names shared by elements you want to style or select together.title: extra information shown as a tooltip on hover. Do not rely on it for important content, since touch screens and keyboards cannot easily reveal it.lang: the language of the element's content.hidden: hides the element entirely.
Other attributes belong to particular elements, such as href on links and src and alt on images.
Expected page text
A paragraph is an element. Attributes add extra information. A link with three attributes
Boolean attributes
hidden in the example has no value. For boolean attributes, presence means true and absence means false. Writing hidden="false" still hides the element, because the attribute is present. To turn it off, remove the attribute.
Comments
<!-- like this --> is an HTML comment. Browsers do not display it, but anyone can read it with View Source, so never put secrets in comments.
Quoting values
Quotes around attribute values are optional when the value has no spaces or special characters, but always quoting them avoids subtle bugs. Attribute names are case-insensitive; write them in lowercase.
Common mistakes
- Reusing the same
idon several elements. Anidmust be unique; useclassfor groups. - Adding a closing tag to a void element, as in
</br>. - Writing
hidden="false"and expecting the element to show.
Summary
- Attributes go in the opening tag as
name="value". - Void elements like
<br>and<img>have no closing tag. idis unique,classgroups elements,titleadds a tooltip.- Boolean attributes are true when present, whatever their value.
Quiz: Elements and attributes