HTML Class and ID
The class and id attributes give a name to an HTML element. With these names, CSS can style the element and JavaScript can find it.
The class attribute
A class can be used on many elements, and one element can have more than one class (separated by space). In CSS, a class is selected with a dot.
<style>
.note { background: #fff3cd; padding: 8px; }
.big { font-size: 20px; }
</style>
<p class="note">This is a note.</p>
<p class="note big">This is a big note.</p>
<p>This is a normal paragraph.</p>
Output in the browser
This is a note.
This is a big note.
This is a normal paragraph.
The id attribute
An id must be unique. Only one element on the page can have a given id. In CSS, an id is selected with a hash sign.
<style>
#main-title { color: darkblue; }
</style>
<h1 id="main-title">Welcome</h1>
Difference between class and id
| Point | class | id |
|---|---|---|
| Use on | Many elements | Only one element |
| Many on one element | Yes, separated by space | No, one id only |
| CSS selector | .classname | #idname |
| Also used for | Grouping similar elements | Unique element, links to a part of the page, JavaScript |
Link to an id
An id can also be the target of a link. Add #idname at the end of the URL, and the browser scrolls to that element.
<a href="#contact">Go to Contact</a>
...
<h2 id="contact">Contact</h2>
This is how you create a link to jump to a part of a page.
Naming rules
- Use lowercase letters, numbers and hyphens, like
main-menu. - Do not start with a number and do not use spaces.
- Choose names by meaning (
error-message), not by look (red-text).
Summary
classis for groups,idis for one unique element.- CSS uses
.classand#id. - An id can be a link target.
- Next: HTML Styles.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |