CSS Selectors: Use Classes

I have refactored a lot of web pages the past thirteen years. When CSS came out, I was ecstatic; my mark-up was much cleaner; style changes were simpler; life was more enjoyable. However, I have also refactored a lot of CSS. Changes to styles are a given and are simple to make–that’s the beauty behind it. The pain comes in when mark-up changes. Mark-up changes often lead to changes in selectors.

Pain is at its worst when selectors are anonymous, whether as inline styles or ones that are dependent on element ordering and hierarchy, such as:

div > p > a > span
div > p img

The mark-up they style is highly susceptible to change as a site evolves. It is prudent to construct base element selectors (body, p, img, etc.) after starting from a clean CSS slate, but anonymous ones should be avoided.

The second is the use of id selectors over classes. Although not anonymous, they lock you into styling just one thing on the page or complicate styles by prefacing them with numerous selectors:

#warning, #attention, #exception { color: red; }

The minute you decide to add an #error element to your page, you’re refactoring your CSS again. Even though you may just want to style just one element on the page when you first define it, it doesn’t have to be selected by id; you can select it by a CSS class:

.attention { color: red; }

If you add a #warning or #error element later on, which you want to style the same, you can simply use the class you’ve already defined and not have to add yet another selector to the list.

I am now at a place where I have largely abandoned anonymous and id selectors and have stuck to just base element and class selectors. Styling is easier and simplicity, readability, and consistency come as added benefits. Of course there are exceptions to this way of thinking–that’s why id and anonymous selectors exist. They just shouldn’t be the default way of thinking.

4 thoughts on “CSS Selectors: Use Classes

  1. i dont see anything wrong with:

    div#navigation ul ul ul ul li {display:none;}

    it makes perfect sense.

    but what you say does go hand-in-hand with over div-ing.

  2. Because it starts with div#navigation it’s more of a relative selector than an anonymous one.

    Small nit: use >’s whenever possible. Child selectors are much more efficient than descendant selectors.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.