I disagree with the idea of never using IDs for selecting elements, however I do understand the reasoning.
Oftentimes developers will use a very high specificity selector when the general form will suffice:
#foo #bar #baz .something a {
text-decoration: underline;
}
is probably better written as
.something a {
text-decoration: underline;
}
Additionally, writing styles like:
#foo-1,
#foo-2,
#foo-3,
#foo-4 {
color: #F00;
}
are better written as:
.foo {
color: #F00;
}
Where I differ from CSSLint involves structural IDs that are reused.
I often mark up pages with this structure:
And because I know that structure is consistent, I don't mind using #page
, #header
, #nav
, #wrapper
, #content
, #sidebar
, and #footer
in my css for sweeping region-specific styles. These styles are tightly coupled to this particular structure, which makes them less reusable; because I reuse the structure, they are reusable. The important thing to remember is that using an ID in a selector is very specific, and should be used sparingly.
A few words on specificity:
Generally speaking, one should use the lowest possible specificity selector that makes the correct selection:
If you're targeting all
elements, then it makes sense to use a
.
If you're targeting all
elements within , then it makes sense to use
.foo a
.
If you're targeting all
elements within
, then it makes sense to use
#bar a
.
However, you
could use a lower specificity selector.
[id="bar"] a
has the same specificity as
.foo a
, which means that you can still target specific elements by ID without creating selectors with unnecessarily high specificity.
I do not generally recommend using [id="XXXX"]
selectors for selecting on the [id]
attribute, because it's verbose and may cause confusion. I do recommend using [data-id="XXXX"]
selectors for selecting based on custom [data-*] attributes to more closely relate styles to the current state of DOM nodes.