Quantcast
Channel: GlacierAgWeb » CSS
Viewing all articles
Browse latest Browse all 3

Write better CSS: Don’t use IDs in selectors

$
0
0

There’s a tool out there called CSSLint that you can use to measure how “good” your CSS is, according to the opinions of a bunch’o’smartypants. Incidentally, it’s included in SublimeLinter — go learn how to install it if you feel like it.

One of the rules proposed by CCSLint is to “disallow IDs in selectors.” I tend to agree; it’s been some time since I’ve written an ID in a stylesheet, and my work has certainly improved as a result.

The worst thing about badly written CSS is that it breeds even worse CSS. IDs contribute to this issue because a) they are unique and cannot be reused, and b) they have a higher level of specificity than classes, meaning you need to write longer selectors to override them.

Consider this example:

#header a {
    color: OldLace;
}

If you’re expecting to have only a single OldLace-coloured link on your entire site for the rest of time, then this will be a good decision. However, if you’re not so sure, then it will be a bad decision. You’d have to write another rule, instead of just reusing a class-based rule:

#header a {
    color: OldLace;
}
#fashionable-link {
    color: BurlyWood;
}

Furthermore, when you have more than one link in #header (I know, it’s crazytalk), then you need to do one of these:

#header a.not-oldlace {
    color: SeaShell;
}

And lo, bad CSS breeds worse CSS. Before you know it, you have stylesheets full of ultra-specific styles, exceptions to those styles, and a guilty smattering of randomness at the bottom of a file because you have no idea where to put your new style that’s overriding another style declared on line five that was overridden on line 208, and then again on line 621.

Keep them IDs outta your CSS selectors, Jolene!


Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images