Categories
Frontend Technology

Don’t use IDs in CSS

This article originally appeared on my first blog, f055.net

Broken window blinds.

In CSS, you can assign styles to elements in 3 ways: either by a direct reference to an HTML tag, or by a class attribute, or finally, by the id attribute. Each of these approaches has it’s pros and cons, but in this article, I’ll highlight why you should avoid using styling by #id. In fact, you shouldn’t base your style design on id attributes at all.

#id can’t be reused

The biggest flaw of id styling is explicitly declaring that this style can be used just once on the whole page — because an HTML id has to be unique. Imagine you design a page and in initial assumptions, you define a top ad box by id. Now time goes by, and you want to have this ad box style replicated at the bottom. You end up making changes in the CSS, instead of just copy-pasting ad box code, if you had used a class to style it.

#id can’t have multiple references

The second biggest flaw is that id styles can’t be added up in one attribute as it can be done with classes. This is really annoying when you want to minimize you CSS and use pieces of style here and there and be flexible about it. It’s perfectly ok to attribute an element with classes like that:

class="twitter sidebar"
class="large google sidebar"

But you would never get away with it in id attributes.

#id style can’t be modified by JavaScript

Because DOM is based on retrieving elements by IDs, it causes problems to change that ID to give a different look to an elemenet. Again, it’s perfectly ok to manipulate the style with classes, changing the className value. You could go doing that all day with great effects.

Conclusions

I’m not saying styling by #id is bad. But it may create problems in the future, because it’s not flexible enough, and the gains over class styling are purely semantic. In fact, there’s nothing wrong with defining a class and using it just once — as if it was an id. And if you decide that actually you’d like to use it again somewhere else, you are not bounded by anything. So why not to?

By Marek

I graduated Oxford University Computing Laboratory in 2008 and since then have been a full-stack lead on many projects, in different technologies. Myself, I like to code in Perl, Solidity and JavaScript, run on Debian & Nginx, design with Adobe CC & Affinity and work remotely, but overall I always do whatever gets the job done. I like to learn new things all the time!

Leave a Comment

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