In college I worked at a bar. The bar had a small kitchen and served typical American bar food: burgers, wings, and soup. We had two soups, one would rotate, one was always chili. We hand-made the chili every week. Sometimes we would sell out, sometimes we’d have chili leftover at the end of the week. If there was leftover, we would either throw it out or take it home. It was still perfectly good to eat, just not a good policy to sell week old chili at a restaurant.
I worked at this bar with a friend of mine. He was a vegetarian. He wasn’t a vegetarian for taste or personal health reasons, but for global sustainability. The chili had meat in it. So, typically off the menu for my friend.
One particular end of the week rolls around and we have leftover chili. My friend is working. He could dump this pan of chili down the drain, or he could take it home. Now, if you’re a vegetarian and you are a vegetarian solely for the purpose of global sustainability, surely the correct choice here is to take the chili home and eat it. Throwing away food and consuming something else is wasteful.
Yes, he could bring it home for me or bring it to his grandmother’s house. We could think of 100 alternative paths for this chili to take, but let’s stay in the analogy here – it does come up where one’s personal ideals are challenged by practicality. Sometimes it involves chili.
When this conundrum was discussed with my friend, I thought he presented a good argument for his not eating the chili. He said: “it’s about drawing a line in the sand.”. In all likelihood, he was probably referencing The Big Lebowski, but he went on to make a good point.
This isn’t about one pan of chili and one guy at one bar. It’s about not compromising for the long term and greater good. Maybe next time the bar makes chili, the bar will make a bit less or make it in smaller batches due to known waste. Maybe next time the bar revises the menu there will be less meaty stuff because we know there are uncompromising vegetarians like my friend who spend a lot of time at bars too. If this attitude becomes the standard, it becomes about millions of pans of chili and a changed world.
Right, so, HTML classes.
You know that it’s generally best to style with classes right? This is what OOCSS and SMACSS and modern writing about CSS is teaching. Not just “use classes smartly” but also “don’t use ID’s”. CSS Lint event tosses you a warning for using ID’s in selectors. What? Really? An error for writing a perfectly valid selector?
Yes, really. ID’s are infinitely more specific than classes. Well almost. That’s so strong it can get out of control quickly in CSS. Yep, it can be a quick, easy, powerful override, but then how do you override that? (Who watches the Watchmen?) If you agree with yourself (and team) to never use them, you don’t get in these arms races. These override predicaments can always be solved another way – through code refactoring, nesting a class, or something else calmer and more intelligent.
Plenty of smart people disagree with this (see comment thread on another post). But to me, this again comes down to drawing a line in the sand. I’m not going to use ID’s to style things. No compromise. Even if an ID might seem like it could save me in a short term way, the long term benefits of never using them are greater.
One day I just decided to draw my own line in the sand and I haven’t styled with an ID since. Once in a while it might feel like it defies logic, but overall I feel like it has improved my work.
Great, now all I can think about is eating chili…Oh, and doing a little “find ‘#’ -> replace ‘.'”
I just did this and was freaked out because everything was broken. Then I realized that I had nullified all of my colors. :(
are not tags like header, footer, aside, and nav just pseudo IDs? this is certainly one of the ways I consider them. I suppose if you use only one in your code, then you would not need to add a class or ID to it for styling.
I remain to be convinced that IDs are no longer useful or usable.
Al
Tags are selectors. An ID is a one-time use on a tag in place of a class.
class=”foo” (use as much as you like)
id=”foo” (use once)
IDs still have their place in JavaScript / jQuery though!
It’s actually perfectly valid to have multiple headers, nav, or asides (I think you are limited to one footer). You may have a main header, and then you may have a header in each section tag for example.
I don’t think Chris was saying that ids aren’t useful. You can use them in CSS and they are awesome for js. But it can help to keep things sane if you stick to classes.
My team had used an id for a submit button. They thought there would only every be one submit button. They were wrong and I had to convert the id to a class. Not a big deal, but using class can make things easier.
I agree, ArleyM, using IDs is still the most efficient way of manipulating elements with scripting languages. getElementById is tremendously speedier than all other alternatives because the browser keeps an index of elements with IDs, and it returns only one element. Sure, we have getElementsByClass name, but first the browser has to iterate over every element, looking for that class, and then you have to iterate over the results again to find the element you’re looking for.
You may argue that jQuery would solve the complexity issues, but it’s still doing all of the exact same logic behind the scenes.
If you care about script speed, you use IDs.
I think a blanket ban on such a fundamental part of HTML is wrong. They are tools to be used with wisdom and moderation. Let’s not overreact here. A lot of people misused tables, and we scared everybody into stopping table use altogether. Some people misuse IDs, but let’s not make the same mistake again.
Read what Chris says:
“use ID’s to style things”, i.e. write CSS to style the elements with a certain ID. So that has nothing to do with JavaScript. I guess he will still use ID’s to target the element with JavaScript.
In a way this link is completely unrelated, but in another it brings the sand / chili analogy full circle. I coincidentally read this this morning:
There’s actual sand in fast food chili: http://www.businessinsider.com/11-disgusting-ingredients-that-arent-advertised-in-food-2012-3?op=1#ixzz1qYZOG1QU
Your friend could now get into metaphor sustainability and draw a line in the chili!
What about using an ID as a fragment identifier within a document? http://www.w3.org/DesignIssues/Fragment.html
Fragment identifiers are not not CSS. This discussion is purely about using IDs for styling hooks. Of course IDs should still be used for other purposes.
Good point.
I couldn’t agree more, although I must apologise in advance for being a total smartass…
A quick view source of this page shows up 47 uses of ID’s. Ok, fair enough you’re not using these for styling purposes. But wait, there are a number of declarations for ID’s in the page’s stylesheet too.
So is that “line in the sand” for you in the future? Or is there a legitimate reason why ID’s NEED to be used in certain circumstances?
That’s one of the things I hate about WordPress. I try hard to write clean, best practice code in all my projects, but then my personal blog (which people will assume is supposed to represent my best work) is a mess. Because WordPress is awful when it comes to code, especially when you have tons of widgets and plugins. In many cases, those plugins are the only ones that do what you want, and the only styling hooks they offer you are IDs.
From my quick look at Chris’s code, it seems this is exactly what he’s done. So in a nutshell: WordPress doesn’t count! :)
(Which also is why when you view source on Paul Irish’s wordpress blog, you’ll see the message: “This site’s own code is pretty weak…”)
Ah that explains it then! I’m not a user of WordPress, and this is another simple reason why. I’d feel pretty uncomfortable using a CMS which bastardises your code in such a manner.
@Louis – I don’t think that’s WordPress’ fault at all. You can blame plugins, sure, but as I developer I always feel like the theme itself is completely within my hands to control.
@gary:
I agree, but admittedly, on a personal blog, laziness trumps best practice! :) It’s just easier to allow WP to be crappy, that’s all.
Also, with regards to plugins, the problem is this: The plugin will often insert the HTML on its own. Yes, I could go in and edit the plugin file so it has classes instead of IDs. But then what happens when I upgrade the plugin? Those classes disappear, and it breaks things. And there’s no way I’m going to make special notes on every plugin I manually change. Thus, it’s just easier (read: lazy) on a personal blog to let WordPress have crappy code. So I know it’s possible to make it better, it’s just not often very fun or practical.
woops… “gary” is supposed to say “gray”. My bad. :)
Disagree about the WordPress comment– The dev has 100% control over the markup, WordPress does not bastardize anything. If you choose crap plugins, that is your own fault. Choose your plugins wisely, grasshoppers.
The better I’m getting at building CSS, the less I’m using ID to style things.
But then again, I still use them, because there are some elements that are actually unique, and needs to be unique. ID rules are perfect for them.
What I know is that I’m saving time in the moment I write the rule. Would I save time using a class instead? Well, who knows? How can I compute that?
I hardly can. And even if I could, I’m not sure it’d be worth the effort.
If I ever want to protect my ideological integrity, I’d say I want to be able to draw a line in the sand whenever I feel like it. That line could lead me to the right path.
Just because an element is unique, doesn’t mean its styling is unique. Why not use a more generic class that could be applied to something else?
And just because something is unique now, doesn’t mean it will always be unique. You think you will always have only one header, one footer, and one content area?
@Scott
When I say that an element is unique, I mean its styling is unique. So there.
You don’t know what I call “unique”, and why I’m sure they’re unique. Do you honestly think I’m just talking about headers?
There are also cases where I mix ID and classes. It’s something I can do, so I do it when I need it.
In the end, I think that using ID rules is semantically more correct than using classes only.
MaxArt, I am unsure you’re grasping the concept. Once you commit to styling an ID, you are saying “I will never reuse any of the styles applied to this ID on anything else, ever.” If what you’re building is designed in a consistent/user-friendly way, I would argue that there are cases for reusable styles in every “module.”
Merne, the point of an ID is to make an element unique in that page. I can use the same ID in many pages.
For example, if I want to cover the whole page with a waiting spinner when an AJAX request is made in order to prevent further user interactions, I can use an unique structure to do so. And I can use it in all the pages I want, in a consistent way.
Sure, I can use classes. But why? Is there any chance to have more than one full-size cover in the same page? No, that would be an interface bug.
Using just an ID is the semantically correct way to do the trick.
You bring up a good point for a very specific use-case. In this case, I agree with you. Of course, this loader has no semantic meaning, so it would be added via javascript (if I were doing it), not be present when the DOM loads. I use IDs in my javascript, so in this case I would use an ID as well (but have a class that I use for styling).
The point here is that if you decide to mix IDs and classes (in your stylesheet), you’re starting a specificity war. I agree that certain developers can get away with it (and do it beautifully), however, if the instance comes up where you are not the only developer things can get hairy quickly.
All that said, I don’t think IDs have anything to do with semantics.
Exactly!! Thats what I tell my team mates..hope your post now makes them aware of the stuff..just shared on facebook! :)
I remain unconvinced. I use ID’s now and then, when it’s a very specific case.
Why would I need to override it – it’s a specific selector for a specific element, so I can just go and change the contents of that selector. I know it won’t impact anything else, because it is unique.
Sure, if you chuck ID’s all over the place and use them as selectors then you’re bound to run into trouble sooner or later, but if you use them here and there in very specific scenarios, I can’t see the issue.
In the CSS Wizardry article you linked to in your Crazy Town Selectors blog, the concept of “selector intent” came up. Ask yourself what you’re selecting, and if your answer is “this element and this element alone”, then why not use the ID? If the answer changes, then yeah you need to swap it out for a class or shared selector, but that’s because the intent has changed, and the ID is no longer appropriate.
Rather than a restrictive line in the sand that says “don’t ever do this under any circumstances”, I think it is more appropriate for a guideline in the sand (see what I did there?) to prevent ir deter abuse.
I still pull people up on their use of ID’s when it isn’t appropriate, when they’ve got duplicates’ or when their selector contains pointless ID references (i.e. 2 stacked ID selectors). But that’s quite different from telling them to never do it ever.
Yeah I’ve since adopted the no more ID’s theory. I look at older websites I built and think “Ugh.. what a mess” when I was overriding the ID’s in all these weird ways. Classes make everything SO much cleaner.
Estelle Weyl’s “CSS SpeciFISHity” graphic is awesome for visualizing how different CSS IDs and classes are in terms of specificity.
I think those who oppose the “no ID in CSS” ideology are missing the big picture.
To write maintainable, scalable CSS that will grow and mature with a site, you need to think of each section of your page like a module, and not just a single module but a build up of pieces, from very generic modules to sub-modules that get more specific. In doing this, you see the value of using classes over IDs. If I decide to use an ID on a sub-module, then I can never build upon it to reuse those styles elsewhere because that selector is now too specific.
Just look at how Twitter Bootstrap is built, where you have classes like
.nav
and then “sub” classes like.nav-tabs
. You have a base class like.nav
which is then built upon with.nav-tabs
. This is the way you should be thinking about building every part of your page. Can it be generalized into a base class that I can then use over and over on my site? Even “unique” elements like a main navigation still benefit from base classes. You could construct your CSS in a such a way that your actual rules for your main nav are only a few lines because it relies on other base classes to do most of the work.You’re bringing up a very trivial example.
You can use the same ID in more than one page too, you know.
This is a good description of why we should draw that line in the sand. I was looking for a deeper explanation of why “the long term benefits of never using [id’s] are greater.” I would like to read more about that.
Excellent example.
I definitely agree with you Chris. Unless you are working with PHP. But even then, I do not recommend styling an ID.
Tags, like header, footer, aside, nav, section, article, are not like id’s, they’re tags. They are used in styling as tags. It means you need that many less classes, but leaves the possibility open.
For instance if you want to have primary and secondary nav. One may be horizontal and the other vertical. In a case like that you can use the nav tag for both, and give each a class. So links may look the same, but have different font sizes or whatever you like.
Yo, just FYI, but I fixed our “classes can be more specific than IDs” bug in WebKit. Now class specificity will just clamp at 255 and not overflow into ID territory.
But you are not going vegetarian? : (
Where is my happy ending?
I’ve come across these discussions quite a bit recently, but have yet to hear a good reason not to use IDs.
In my case, I use them religiously to identify (ID) certain parts (modules, sections, whatever) of the web site or application. That way I can write a bit of generic styling declarations for the whole system via tags and classes; and can then use the container IDs to target specific instances of a more generic pattern that may need some additional (or different) styling.
This practice has served me well in keeping the size of my stylesheets down and making it easier to maintain and modify styles in the future.
I’ve converted to using classes on pretty much everything. I still use ID’s for cases where Javascript needs them or for semantics, so for example;
So I’m using grid one-third (for example) for doing the width, height, styling etc and then main-content is there to specifically target with JS or indeed just for semantics, I very very rarely use them for styling anymore.
Hmm, couldn’t get pre/code tags to work. Anyway – I meant;
div id=”main-content” class=”grid one-third”
For example.
But what about when you have 3 of the same grids on a page, and you want the #main-content to be slightly different?
If the style I needed was just for that DIV uniquely then absolutely I would probably style the ID. However, if it was a repeating style, color, background, box-shadow whatever, I’d find a way to create a class to effectively “opt-in” the div and simply add an extra class.
It’s easy for people to fall trap to the law of the instrument, and when they realize they’ve been foolishly abusing a tool, the common knee-jerk reaction is to stop using the tool altogether.
This is foolish behavior.
Instead, learn when it’s appropriate to use a tool, such as when ID selectors are a reasonable solution.
If the tool isn’t appropriate, don’t use it.
Chris, I have followed you for a long time and many of your diatribes end up sticking with me and making me into a better person/developer… no matter how much I disagree with you at the time. However, I have never heard you talk in such absolutes, and I come back at this post by saying that speaking in absolutes is never a good thing. Would you argue that IDs have no purpose in web development, or just not for styling?
Chris says right in his article that “[He’s] not going to use ID’s to style things. No compromise.” I can only assume that he was meaning that using IDs for other uses is fine – like jQuery.
Can we see an example of someone using IDs to select in a dirty fashion?
If I have a login CTA with the ID “login,” I am going to use that ID to create a tiny, lovely selector for that very unique UI element. Shortly afterwards, I will treat myself to chili as a reward for my eloquent confluence of HTML, CSS, and JavaScript.
And now, the client wants to add that same login to the footer as well…
I only use classes except for when I’m targeting an anchor on a page, which is rare in itself. Id’s seem more useful for function than styling.
It’s a small thing, but periods (.class) are also less visually distracting/obtrusive than #’s in CSS. Silly, but it’s true!
For years and years – probably longer than I even knew there was any reason not to – I’ve never used IDs for styling EXCEPT in one instance. For me, the reasoning was always merely “did I call this #mani-nav or .main-nav”? A little annoyance that can add up over hundreds of selectors.
The one except – and proabably one I’ll still keep using – is that I use any ID only ONCE in a PROJECT and then only on the <body> tag. In addition, I never use IDs in CSS to style except in once case:
or some such. It just seems to me that IF the ID tag had a legitimate usage it was to label a page for ‘IDentification’ purposes – and perhaps the fact that it goes against the ‘ether’ to use double .home.home.
My personal path from IDs to classes: I used IDs more in the (recent) past… I typically had this way of thinking:
1) a “unique section” inside a page was identified by an ID
2) everything inside it was styled trying to avoid “divitis” and “classitis” i.e. using appropriate tags for contents and avoiding adding unneeded classes to my HTML:
‘#’news {}<br/>
‘#’news h2 {}<br/>
‘#’news ul {}<br/>
‘#’news a{}<br/>
(Maybe this could have been done with classes… but, hey, that was the past!)
Now that I moved to HTML5 (more semantic tags, wow!!) and LESS, I found myself trying to draw that line.
I definitely think that mixins and nesting made this possible. I’m still experimenting but it seems to work fine…
Another thing that helped me a lot in writing better CSS is making the site style more “consistent” across pages and sections (i.e. avoid unnecessary and meaningless variations)
Hey I was told I could get a free bowl of Chili if I came here….
.totally-agree
Before propagating a particular method you should ask yourself what is the goal to achieve.
So which goal you would like to achieve when writing CSS?
Assumed you want to write the most efficient code, how can you do this?
And once again you have to ask what “best efficiency” means in this case.
Smallest file size, minimal overriding rules, best maintainability, upgradeability or what else?
So at least several of the above could only be achieved when the HTML markup of your whole site is done and you regard it as completely static. In other words this means you have to write all of your HTML first and then start to write your CSS, but who really does it that way?
To avoid that a small change in your markup leads to changing or rewriting huge parts of your CSS, classes are undoubtedly an appropriate (the best?) method. One of their biggest advantages is that they make your CSS more independent from the structure of your markup and so offer a greater flexibility to code changes. And classes could also be easily manipulated by Javascript.
I could imagine that most people rarely use CSS classes cause of the thinking to keep their HTML code as tidy as possible but instead try to do it on the CSS side by using such fragile constructs like “header > h1 + p {…}”.
And why are IDs so popular?
Well I believe they are, because they offer the possibility to restrict the rules to a manageable part of the page/site. And because of their specificity they ensure that the styles are supplied no matter which other selectors match.
But even with the extensive use of classes you are still caught in the cascade and specificity concept of CSS. Just think about “Responsive Design” and the use of Media Queries for example. So in the real world you (often) will have to apply several classes to one element and also to concatenate them in your CSS (a typical use case is the usage of Modernizr).
And if you later add a new page to your site are you still aware of all your classes you have previously defined in your CSS?
And you won’t change an existing class later on because the effects are incalculable.
The question is:”Why should I?”
You can easily group your selectors when adding a new ID or change a former ID to a class and so on. And as CSS totally depends on the markup it is unavoidable that certain changes to your markup entail also changes to your CSS.
IMHO it is a fact that CSS is at least a little bit inefficent by nature. But do we really have to take care of it?
Don’t forget about accessibility skip menus! We need IDs for that, and for better JS performance.
I just have to thank you for your http://shoptalkshow.com/episodes/034-with-jeremy-keith/ – where he describes re-using html5 elements (like header) with ARIA roles to achieve specificity. This advice has cleaned up and entirely changed my markup forever. Thats my line in the sand!
Using IDs is Ok, really.
You may need to be ‘smarter’ in order to know how and why to use them. ‘Smarter’ than the guy that FFOI only uses classes.
Besides, the REAL name is “chile” not “chili” – Chile Mexicano
Generally I use only classes myself (when possible – wordpress you joker, i’m looking at you).
Not really sure why I got into that mindset. I vaguely remember reading years ago that there was a performance advantage to using classes. I’m guessing it’s slight overall but I’ve stuck with that approach ever since.
Contrary to what you read, I read that actually ID’s have better performance.
They certainly do have better performance, the whole document needs to be traversed to select all classes but the ID element only needs to be found when using an ID selector. I’ve never really seen performance of CSS to be a big issue apart from when using some newer CSS3 techniques.
I feel somewhat hessitate to drop my use of IDs all together. Being highly technical, showing what I was thinking when I wrote code is very important, ie. there is only ever meant to be ONE main-menu and the page is invalid if there are two.
Still with good naming you’re not losing too much and it should hopefully result in more general code as Chris says.
Chili should never be wasted! Anyways, I use IDs and classes to differentiate top hierarchical styles from others. I dont agree to drop them altogether.
What about forms, are they a special exception or should we still use the “for” attribute along with an ID on the label?
If the form element is inside the label, then no need for the
for
attribute.If you want to use an ID on the label, that’s up to you. If you do end up using, rest assured, it’s totally fine.
So if you only use classes, couldn’t you just use ID’s only also? Because outside of specificity and the general rule that ID’s should be unique I don’t think there is any difference? Or is there an actual difference in how browsers would render/cache/performancesomething ID’s and classes?
Good point. However, using only ID’s would prove to be near impossible to reuse components.
As far as OOCSS, using only ID’s would be the antithesis, and we all know that OOCSS is a good practice.
I think I once heard (or read) Aaron Gustafson in a web design conference that ID’s actually had better performance than classes. Gotta ask the guy again, doesn’t seem to be anything out there about this topic.
I couldn’t agree more Chris. When I first heard of it, my eyes opened wide but it makes my life much easier.
Y you no use ID’s?! Often times there ARE elements that are only on the page once. You’re a smart lad, surely you would just know when and where to use an ID over a class?
Why can’t you have IDs and OOCSS? Couldn’t you have something like and get the benefits of IDs and OOCSS?
Ahem,
Something like* <element id=”specific_stuff” class=”generci_stuff />
I find out some wisdom in this article. More important than the Ids/classes fight, (I personally don’t use IDs), is the fact that after thinking and investigating, you take a decision you think will help the way things are made word wide and put your one’s bit.
I still use ID’s but I know that I shouldn’t and will be drawing a line in the sand.
The Dude Abides
once I started really understanding css I stopped using IDs because during development I inevitably would want to reuse code and then have to change an ID to a class. It all started because there was something I wanted to do that only worked on a class, and that’s when IDs went out the window for me.
However, even though I’m habitually using classes, there are places I could use IDs. One example is if I’m using the same class more than once on a page but I want them to be slightly different, i.e. different background color or background image or a different font or line-height. In this case you could use an ID to alter them. I use classes out of habit though and in cases like this I still tend to use classes. Oddly enough the only place I still use ID is on forms. Go figure.
I agree with D, once you really understand CSS, you stop using IDs. Except for the case, when you won’t reuse the code. Once I understood it, that changed my way of thinking about CSS and developing, because reusing of codes can save a lot of time.
What we really need is a way to achieve oocss purely in the css. Having to change class attributes in the html of our templates when a design tweak is needed rather than just tweaking css files feels like a step backwards.
I never use ID’s for styling and I try not to use them in any other way. It just not feels right.
ArleyM and Andy Griffin have both pointed out that the use of jQuery would justify the use of Ids since it’s one of the most common optimization tips given for jQuery scripts.
You yourself (Chris) said and proved very often how jQuery is important in your work.
So my question is: would you say that when using jQuery:
A- using Ids is ok as one of those situation where you “have to” as said by Ben Frain (http://benfrain.com/never-use-ids-as-selectors-unless-you-have-to/)
B- the speed benefit of using Ids is so tiny compared to the benefit of not using Ids in my work that I won’t use them
C- there’s no real speed benefit to using Ids, it’s an urban legend
Thank you