HTML Basics: Build Your First Web Page
Attributes, id and class
In this lesson you will
- Explain what an attribute is and how to write one
- Use id and class to name elements
- Tell the difference between id and class
Introduction
You have already met attributes: href on links and src and alt on images. An attribute gives an element extra information. In this lesson you will learn the general rule, and two special attributes that you will use in every CSS and JavaScript lesson.
What is an attribute?
An attribute lives inside the opening tag. It has a name and a value.
HTML
<a href="https://example.com" title="Visit the example site">Example</a>The pattern is always: name="value", with a space before each attribute.
hrefis the attribute name, andhttps://example.comis its value.titleshows a small tooltip when you hover.
Quick quiz
Where do attributes go?
The id attribute
id gives one element a unique name. No two elements on a page may share the same id.
Run it, scroll inside the result, and click the link. Links that start with # jump to the element with that id.
The class attribute
class puts elements into a group. Many elements can share the same class, and one element can have several, separated by spaces.
The class and id names do not change how the page looks by themselves. Later, CSS and JavaScript will use them to find elements.
id or class?
- An id is for exactly one element. Use it for one special thing.
- A class can be shared by any number of elements. Use it for a group of similar things.
When in doubt, choose class.
Try it yourself
The page below uses a class twice. Add a third paragraph with class="note", and give your h1 an id called title.
Quick quiz
You have three paragraphs that should all be treated the same way. Which attribute fits best?
Summary
- Attributes add information, written as name="value" inside the opening tag.
idis a unique name for one element.classis a shared name for a group of elements.- You will use ids and classes constantly in CSS and JavaScript.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading