15. HTML Classes and IDs
What you will learn
- What the
classandidattributes do - The difference between them
- How CSS and links use them
- Good naming habits
Why they exist
Classes and IDs are names you give to elements. CSS and JavaScript then use those names to find and style the elements. Links use IDs to jump to a spot on a page.
The class attribute
A class can be used on many elements. One element can have several classes, separated by spaces.
Example
<p class="note">Remember to save your file.</p>
<p class="note important">Back up your work.</p>
The id attribute
An id must be unique. Only one element on a page can have a given id.
Example
<h2 id="contact">Contact us</h2>
Class versus id
| class | id | |
|---|---|---|
| How many elements? | As many as you like | Exactly one per page |
| Several names on one element? | Yes | No |
| CSS selector | .name |
#name |
| Jump link | No | Yes: href="#name" |
Using classes with CSS
This is a preview of CSS. A dot selects a class.
Example
<style>
.highlight { background: yellow; }
</style>
<p>This is <span class="highlight">important</span>.</p>
<p>Read <span class="highlight">carefully</span>.</p>
Output
This is important.
Read carefully.
One rule styles every element that has the class.
Using ids for jump links
Example
<a href="#summary">Go to the summary</a>
...
<h2 id="summary">Summary</h2>
Naming rules and habits
- Names are case sensitive:
Menuandmenuare different. - Do not use spaces in an id. In a class attribute, a space separates two class names.
- Choose names that describe the purpose, such as
card-title, not the look, such asbig-red. - Use lowercase letters and hyphens, for example
main-menu.
Common mistakes
- Using the same id on two elements.
- Forgetting the dot (
.) for classes or the hash (#) for ids in CSS. - Writing
class="#note"orid=".note". Symbols are used only in CSS, not in the HTML attribute. - Giving names that describe appearance and then changing the appearance later.
Exercise
Write a paragraph that has the two classes card and featured and the id intro.
Show solution
<p class="card featured" id="intro">Welcome!</p>
Knowledge check
1. Can two elements share the same id?
No. An id must be unique on the page.
2. Which CSS symbol selects a class?
A dot (.).
3. Can an element have more than one class?
Yes, separated by spaces.
Summary
- Use
classfor groups of elements andidfor one unique element. - CSS uses
.classand#id. - An id also works as a jump-link target.