Chapter 4

IDs

Semantically speaking, we should use an ID when there's only one instance of a thing. And we should use a class when there are several.

However, IDs overpower class names by orders of magnitude, which is a problem when we want to override a style.

To demonstrate the problem, let's override the colour of an element from red to blue using an ID.

Here's the HTML:

<div id="module" class="module-override">

And the CSS:

#module {
  color: red;
}

.module-override {
  color: blue;
}

The element will be red even though the override class declares blue. Let's fix this by swapping the ID for a class:

<div class="module module-override">

And the CSS:

.module {
  color: red;
}

.module-override {
  color: blue;
}

Now, the element is blue—problem solved.

Whilst using IDs for styling is problematic, we can still use them for other things. For example, we'll most certainly need to use them to connect:

Final thought

Use IDs whenever you need to enable particular behaviours for browsers and assistive technology. But avoid using them as hooks for styles.

Chapters

  1. Introduction
  2. Semantics
  3. Reuse
  4. IDs
  5. Conventions
  6. Modules
  7. State
  8. Modifiers
  9. Versioning
  10. Javascript
  11. Organisation
  12. FAQs