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

classid
Per pagemany elements can share itunique: one element
CSS selector.name#name
JavaScriptdocument.querySelectorAll(".name")document.getElementById("name")
Typical usereusable stylesbookmarks, form labels, one specific element