Skip to content

Selectors (id & class) ​

The id Selector ​

An id is a name tag you can attach to only one element on a page. In CSS you select it with #id-name.

html
<h1 id="main-title">Welcome</h1>
css
#main-title {
  color: navy;
}

You must not reuse the same id on multiple elements. Think of id as a tool for pinpointing "the one and only element of its kind on this page."

The class Selector ​

If you want to apply the same style to several elements, use class. In HTML you attach the same class="name" to multiple tags, and in CSS you select them with a period (.class-name).

html
<p class="greeting">Hello!</p>
<p class="greeting">Nice to meet you!</p>
<p>Have a nice day.</p>
css
.greeting {
  color: blue;
  font-weight: bold;
}

Only the two paragraphs with the greeting class get blue bold text, and the last paragraph without the class stays as it is.

id vs class: when to use which ​

SituationSelector
An element that appears only once on the page (header, a specific banner, etc.)id
Styles reused in many places (buttons, cards, etc.)class

In practice, class, which gets reused a lot, is used far more often. When you are first learning CSS, I recommend getting comfortable with class selectors first.

Summary ​

ConceptOne-line summary
id selectorUsed to pinpoint the one and only element of its kind on a page
class selectorUsed to apply the same style to many elements repeatedly

Reference: personal Notion study notes