Basic CSS Selectors (Type, Class, ID)

Type Selectors

A type selector (also called an element selector) targets every instance of a given HTML tag. It is the broadest kind of selector and is usually used for base styling that should apply everywhere.

p {
  line-height: 1.6;
}

This rule affects every <p> element on the page, with no exceptions.

Class Selectors

A class selector starts with a dot and matches any element carrying that class in its class attribute. Classes are reusable, so the same class can be applied to many different elements.

.highlight {
  background: #fff3cd;
}
<p class="highlight">Read this carefully.</p>
<span class="highlight">Also styled</span>

ID Selectors

An ID selector starts with a hash and matches the single element whose id attribute equals that value. Because an id must be unique per page, an ID selector should only ever match one element.

#main-header {
  font-size: 2rem;
}

Choosing the Right Selector

SelectorReusable?Typical use
TypeYes, applies everywhereBase/default styles
ClassYes, on many elementsReusable components and utility styles
IDNo, one element onlyA single unique element, or a JavaScript hook

Most projects lean heavily on class selectors because they are reusable and predictable, reserving IDs for unique landmarks like a page header or a specific anchor target.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.