The author of this blog is no longer publishing new posts. Please visit his homepage for links to active projects.
June 09, 2009

Don’t use IDs in CSS

Article about ▸

written by Marek Foss

CSS Class

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?


If you liked the article, please spread the word and share it!


Comments


Also:

#id selectors are really strong

If you begin styling a container using id:
#ad-box a { font-weight: normal; /* because in #ad-box’s parent, links are bold */ }

Then (below) you style for links:
a.important { color: #c33; font-weight: bold;  }

Your ad box links won’t be bolded. You’ll have to specifically use the id again:
a.important, #ad-box a.important { /*...*/ }

Now imagine doing that for each id with all your block combinations and/or classes…
Even if you don’t need it yet. Murphy says you will, eventually.


Never really thought about this, but it actually makes a lot of sense to ditch IDs unless there’s some specific need (like fetching an element via JS)

I’ve usually used mostly classes, but also IDs for things that never should have more than one “instance”, ie. header and footer and such.


So did I, but I ended up having to maintain those when using classes inside them on some cases. That’s why I’d also say as a rule of thumb: don’t use ID selectors at all.


Carl McDade writes:

Well there is a specific need for ID , which is why it exists.

Let take the reverse. What happens if you use Class on a design where the titles are all the same. Then later on you want to change the color of only a single box title on a particular page. Well you can try and stack another attribute in a Class designation for that box. Doing this requires using server side script or some fancy javascript. Not worth the time. The easiest an fastest way is to just use the ID selector on the title.

It’s not a matter of avoid one or the other but in using them both where appropriate. If you are unsure of future changes then use both when designing.


Peter writes:

I completely disagree with the author on this topic. All of the above problems aren’t related to declaring CSS rules on the id attribute, but to improper usage of the attribute in the DOM.


Marek Foss writes:

@Peter: the improper usage is short - don’t use it to style elements, it’s not what it was meant for. In longer words, my point is, don’t enthusiastically use IDs on elements you think will be singular, like bodies, sidebars etc., because you may find yourself with a problem in the future and a need to rewrite pieces of your CSS. That’s all.


Suzy writes:

I too disagree. An ID id for IDentifying a logical of an HTML document (nav, header, sidebar1, sidebar2 etc.) a class is for CLASSifying elements within the IDentified areas. The ID can be used a very specific CSS hook when the two are combined e.g. inside the two sidebars you have blocks but want them different colors/backgrounds so you give them all the class of .block (i.e. you reuse the class many times)

Yu can use the .block class to make all the blocks identical, or you can precede the .block class with #sidebar1 or #sidebar2 to make them completely different using the specificity of the ID.

really don’t think you’ll get far if you ever have to use CSS specificty without those ID’s just remember they are all powerful : http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html :)


Suzy writes:

^ sorry “..IDentifying a logical area/division of an HTML document…”


Mike writes:

I can’t say that I agree, but it is something it was certainly something to think about. I enjoyed reading your argument. Thanks.


Marek Foss writes:

@Suzy: I agree that you are correct in the sense that it’s all “by the book” about IDs and Classes. But in fact, it’s not incorrect to style the nav, header and sidebars using classes. And it has benefits too - on this site, my sidebar is splitted on the front page, but I don’t need a #sidebar1 or #sidebar2, just “sidebar” and “sidebar cont” classes. And I didn’t plan it in the beginning, and had I gone for the ID way, I would have to rewrite quite a bit…


Artur writes:

Totally disagree…

There are specific needs for IDs and CLASSes…

Just saying DONT USE IDs is confusing and lead beginners to error.

If I were you I would delete this article and make another one, explaining where and why use IDs and CLASSes…


ChetG writes:

I can’t say I agree with not using IDs. @Suzy raises most of the reasons why IDs are important in CSS. I do not think that IDs are necessary to implement a great design, this site for example, but they do play a large role in CSS for many designers out there.

@Arthur also raises a great point that this may cause much frustration and confusion with beginners. Not everyone comes into this with the knowledge of how to successfully use classes singularly. They may need/want the stability that the ID has to offer.


Josh Salverda writes:

I completely disagree that you should never use ID’s. An ID is *supposed* to be unique and the element you have applied it to is *not supposed* to be re-used. If all of your elements *are* going to be re-used, then sure, go nuts and use Classes for everything. But really, are you going to have multiple headers or footers? or more than one main navigation?

If you’re using JavaScript and you want to change the style on an ID element, *then* add a class name to be more specific. If you never use an ID in your code, good luck using JavaScript anyways… you will need to find yourself a good Class selector script and then constantly only select the first element in the results (if you’re only looking for one) or loop through all of them. Or you could just use document.getElementById() which is supported in every browser anyways.

The whole point of proper HTML (and CSS) markup is to make the the code easier to read and understand. Looking at your code is confusing as hell. WTF does a class of “box” mean? or “text”? or “strip”? Work on creating a web site that is easy to read and understand the code then maybe I’ll change my mind.

BTW your code doesn’t validate… and you have the same ID defined multiple times, hahaha…


Marek Foss writes:

@Josh: I’m not sure you got my point, really. Don’t use IDs *in CSS*, not ‘at all’...
Also, regarding my code, you obviously didn’t look at the HTML - “entry box”, “post text”, “captions text” classes is as easy and straightforward as it gets. CSS is just a tool, you don’t need expressive names, you can use quotes like in grownup prog languages… It’s HTML that supposed to be semantic.

BTW it’s a Valid XHTML 1.0 Strict now, giving me another case-study for not using IDs in CSS:
My twitter timeline in the sidebar used #t1, #t2… to fade each list element. When I added the RSS subscription paragraph, I wanted to have the same color as #t1, so just made there a 2-element list with id=#t1 - but it’s not valid, is it? So I had to change all Ts to classes both in CSS and HTML. Had I foreseen it and used classes from the beginning…

Also, I know how it goes, I’ve been a geek for long enough. I claim a radical statement on my own blog, then people who disagree either throw concrete arguments (i like those) or try to prove I am lame and shouldn’t even open my mouth (i pity those)... so please let’s be professional about all this, and consider pros and cons.

Has anyone actually read the “Conclusions” in the article..?


ChetG writes:

@Marek I understand why you want to use classes. Especially when you want to style things the same way. However I have to say that if you’ve styled a particular ID in a manner that you’d like to recreate, why would we have to rewrite anything. Could you simply add the new ID to your CSS. I have done that many times. Styled multiple IDs with one set of parameters, however I still kept them separate for other individual changes.

Bravo on criticizing the attackers.


Josh writes:

I will use Id tags the most, I will use classes only where I have to with multiple of the same name. Id tags are higher performance when used with jquer, as the wiehgt hangs on the browser with an Id not on the code, there are certain things you can only do in css with an id and not a class, oh and also the word class is 2.5 times longer than the word id. Id rule (wherever they can be used)


Josh Salverda writes:

@Marek Many, many developers would disagree with you about not using expressive class names. I did read your html, and I still stand by the fact that your class names are not descriptive enough. You’re polluting your html with all these extra “text” “box” etc. classes… just use class=“entry” class=“captions”... You have h1’s wrapped in div’s, ul’s wrapped in div’s, p’s wrapped in div’s… everything is wrapped in a div, what’s up with that? Why not just add a class to the h1? or ul? or p?

Sorry if you feel like I’m “attacking” you, I just think your post was a bit premature and needs some more work to be able to convince experienced developers. You can’t just go around spouting off that people should stop using ID’s without concrete proof as to why. ID’s and classes are completely different, but in your post you compare the two against each other… *obviously* ID’s aren’t as capable as classes, but they were never meant to be.

Maybe if you wrote something about how *you* think ID’s should not be used and how *you* don’t use them (I would probably still disagree, but it’s your choice at that point), but don’t just blatantly state “don’t use ID’s!” to every developer out there. When you do that, people feel attacked and get defensive.


Marek Foss writes:

@Josh: First, let me just start from the end. This is my blog, thus this is my statement, and I don’t think it is necessary to express it more, unless there are people who blindly follow any statement on the “internets” (and I believe my readers - including You - are not).

Secondly, I put out 3 concrete cases as to why IDs are not a good idea in CSS. It’s my claim and something to think about, that’s why I included a “Conclusions” paragraph… And *yes*, IDs aren’t as capable as classes, but they never meant to be used as heavily in CSS as they are now these days. Reconsidering things with IDs was my point.

Finally, I too like to design pages using generic HTML tags, virtually no divs and classes, but sometimes you just can’t get what you want with that. If You or anybody else could replicate my multi-column liquid design without divs but with all it’s features, I’d be happy to write an article on it.

Also, using single “entry” or “captions” classes would mean a lot of duplicated stylesheet code, and that another thing to avoid.

BTW I am happy to see such a live discussion about this, thank you all for participating!


zalun writes:

@Marek Foss 10/06/09 at 16:53:

I do think you used HTML/CSS badly in that example.
“My twitter timeline in the sidebar used #t1, #t2” “So I had to change all Ts to classes”
It is fine, but you should in the beginning make the HTML more semantic. I’d name the twitters #tw1, #tw2 but also add a class called “twitter-message”. It could be also done by grouping them within an element with id “#twitter-messages” or similar, but it’s definitely a matter of choice.

According to your post and thinking of the future. What if you’d like later the first message to look different? Which is logical as it probably is the most actual Twitter message you wrote. You’d have to use Javascript ($$(’.ts’)[0]) or _give_it_an_id_.

It applies to all of your post actually. Group similar elements using classes or by parent element, but give them id’s for (well) identification.

I read the conclusion, but I don’t think I’d agree with it. Id is a very important part of CSS. Use it wise.


@Marek Foss 10/06/09 at 18:59

Your 3 cases are not concrete as they apply to the sentence “use id’s not classes” which is wrong.

#id can’t be reused, #id can’t have multiple references
Right, and they don’t ment to be - use classes instead

#id style can’t be modified by JavaScript
I don’t get it - I do it all the time. You can change the id itself, you can change the class of an element _identified_ by id, and you can change element’s inline style as well.

There is also another point why one _should_ use id’s to mark a unique element. It’s quicker in Javascript. Selecting one specific element in Javascript by searching for a class is longer than using the getElementById function.

To sum my opinion on using classes and id’s.
It’s not wise to use id’s or classes only. They both cooperate in a clean way. One should use both, otherwise a lot of tricks and unnecessary complication is implemented.

BTW. Please excuse any english mistakes - it’s not my mother’s tongue


Jon Krazov writes:

All extremes are wrong. You can get blinded the same way by the light as by the darkness. I agree with Zalun - the best is to use both identificators and classes. In a wise way.


Robert writes:

Any advanced web site will need to use IDs.

Say, you have a list of users on your page and you have one element for every user in that list. Now you want to style every user the same way, so you go:

<div class=“user”>...</div>
<div class=“user”>...</div>
<div class=“user”>...</div>

Now you do an AJAX request and want to update specific user, so how would you do that? The answer is: use IDs! If you had:

<div class=“user” id=“user_5”>...</div>
<div class=“user” id=“user_9”>...</div>
<div class=“user” id=“user_16”>...</div>

you could still use class to style all users and use ID for updating specific users from the AJAX requests and manipulate DOM in general. This way you can also easily use unobtrusive javascript buttons within each user.


Marek Foss writes:

@Robert: Don’t use IDs *IN* CSS - I don’t know how that’s connected with JS operation on IDs…


David M writes:

I never use ID unless i need scripting to work with the element. CLASS is used for *all* CSS.

There is no need at all in any situation (yes i said! i went there!) to use IDs to *just* style using CSS… including layouts. If you need scriptable access to it then add a id=”” but leave the class=”” as the css definition. There is no need to have the # selector appear anywhere in your CSS file ever.

If you can’t read or understand your CSS file or the resulting HTML output and identify what a singular element is, you have MUCH bigger issues to deal with :)

ID’s for Javascript, CLASS for CSS. Just makes sence, and it’s easy to manage…. and easy to merge HTML designers work with the coders work when in real life situations you have to merge files on checkin ;).

All problems are easy to solve too. If you come to a point where you want to style a single element in a group but keep the current style?
<div class=“mystyle”></div>
<div class=“mystyle myextrastyle”></div>
<div class=“mystyle”></div>

done! just too easy.

You can also tell at a glance all coded/dynamic elements on the page which helps you define your styles… i could go on and on and on


David M writes:

@Marek Foss

I feel sorry for you… the amount of people who just couldn’t understand what you meant and lost the plot completely is astounding.


Marek Foss writes:

@David M

Thanks. I agree, I feel sorry for the people who don’t fully understand what they are reading and jump into conclusions that have nothing to do with my point ;)


zalun writes:

@Marek Foss
Could you please show me what gives the impression that I haven’t “fully understand” what have you written? I think that I have to be one of such people as you didn’t bothered to answer to my post.


Marek Foss writes:

@zalun
My post has nothing to do with IDs and JS, and I am not saying don’t use IDs at all - I just suggest not using them in CSS, as their difference between classes relies on a general agreement, and if you’d like to, you could use a class just once and have the same effect, plus have the classes flexibility in case you changed your mind in the future.


Dathan writes:

Attr=0000
Elem=0001
Class=0010
ID=0100
Inline=1000

Use them all to control the specificity.


Leo writes:

Enough with this noise. Dathan said it all.



Leave a comment: (comments may not appear immediately due to page caching)

Name: Email: (not disclosed)

WWW: Remember my details

Notify me of follow-up comments

Feed me:

to feed
  • Subscribe and get the new articles every now and then directly in your reader — I recommend using Google Reader

Facebook:

Connect:

 by Google
Google FriendConnect appears to be down at the moment. Sorry for inconvenience.
Related Posts with Thumbnails