Careeroza
Class & Id
The class Attribute
Example
A class can be shared by many elements. CSS selects a class with a dot (.city):
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
.city { background: tomato; color: white; padding: 4px 12px; margin-bottom: 8px; }
</style>
</head>
<body>
<div class="city"><h2>London</h2><p>Capital of England.</p></div>
<div class="city"><h2>Paris</h2><p>Capital of France.</p></div>
</body>
</html>Result
An element can have several classes separated by spaces: class="city main".
The id Attribute
Example
An id must be unique in the page. CSS selects it with a hash (#banner); it is also used for bookmarks and by JavaScript:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
#banner { background: #282A35; color: #04AA6D; padding: 10px; }
</style>
</head>
<body>
<h1 id="banner">Only one element has this id</h1>
<p>Other content...</p>
</body>
</html>Result
class vs id
| class | id | |
|---|---|---|
| Per page | many elements can share it | unique: one element |
| CSS selector | .name | #name |
| JavaScript | document.querySelectorAll(".name") | document.getElementById("name") |
| Typical use | reusable styles | bookmarks, form labels, one specific element |