When should I use id selectors vs class selectors?


#1

Question

When should I use id selectors vs class selectors?

Answer

We should use class selectors to style multiple elements at the same time with the same styles. Note that elements can have multiple classes applied to them.

However, an element can only have one id and that id value has to be unique to the entire HTML document. We use id selectors to apply styles to a single, specific, element in our HTML document. Also, id selectors have a higher specificity than element or class selectors. This means that we can use an id selector to override styles coming from element or class selectors targeting a specific element. For example, given the following HTML and CSS, we expect the text of our <h1> element to be green:
HTML:

<!DOCTYPE html>
<html>
<head>
  <title>My Site</title>
</head>
<body>
  <h1 class="greeting" id="hello">Hello World</h1>
</body>
</html>

CSS:

h1 {
  color: red;
}

.greeting {
  color: blue;
}

#hello {
  color: green;
}