Grow your CSS skills. Land your dream job.

CSS Style Guides

Published by Chris Coyier

As we wrap up our recent poll on ordering CSS properties, it brings up the larger issue of CSS style guides. Ordering properties is just one choice you have to make that makes up a complete styling strategy. Naming is a part of it. Sectioning is a part of it. Commenting, indentation, overall file structure... it all makes up a complete CSS style guide.

Let's round up some existing ones.

But first... Not Pattern Libraries.

I love pattern libraries. Think Twitter Bootstrap or GEL. I think they are a fantastic way to work particularly in large sites and web apps. This post isn't about those. We'll do a roundup of those some time, because I think that would be valuable too. This is about style guides for CSS itself.

The List

I'll list some excerpts from each that I like below.


GitHub CSS Style Guide →

As a rule of thumb, don't nest further than 3 levels deep. If you find yourself going further, think about reorganizing your rules (either the specificity needed, or the layout of the nesting).

Unit-less line-height is preferred because it does not inherit a percentage value of its parent element, but instead is based on a multiplier of the font-size.


Google HTML/CSS Style Guide →

Use ID and class names that are as short as possible but as long as necessary.

E.g. #nav not #navigation, .author not .atr

Do not concatenate words and abbreviations in selectors by any characters (including none at all) other than hyphens, in order to improve understanding and scannability.

E.g. .demo-image not .demoimage or .demo_image

Idiomatic CSS

Nicolas Gallagher's Idiomatic CSS →

Configure your editor to "show invisibles". This will allow you to eliminate end of line whitespace, eliminate unintended blank line whitespace, and avoid polluting commits.

Long, comma-separated property values - such as collections of gradients or shadows - can be arranged across multiple lines in an effort to improve readability and produce more useful diffs.

Use separate files (concatenated by a build step) to help break up code for distinct components.

CSS Wizardry

Harry Robert's CSS Style →

I have a blanket-ban on IDs in CSS. There is literally no point in them, and they only ever cause harm.

This section heading is also prepended with a $. This is so that—when I do a find for a section—I actually do a find for $MAIN and not MAIN.

In situations where it would be useful for a developer to know exactly how a chunk of CSS applies to some HTML, I often include a snippet of HTML in a CSS comment.

Smashing Magazine

Vitaly Friedman's "Improving Code Readability With CSS Styleguides" →

For large projects or large development team it is also useful to have a brief update log.

For better overview of your code you might consider using one-liners for brief fragments of code.


ThinkUp CSS Style Guide →

If the value of the width or height is 0, do not specify units.

Comments that refer to selector blocks should be on a separate line immediately before the block to which they refer.


WordPress CSS Coding Standards →

Add two blank lines between sections and one blank line between blocks in a section.

Broad selectors allow us to be efficient, yet can have adverse consequences if not tested. Location-specific selectors can save us time, but will quickly lead to a cluttered stylesheet. Exercise your best judgement.

Magic Numbers are unlucky. These are numbers that are used as quick fixes on a one-off basis. Example: .box { margin-top: 37px }.


Jonathan Snook's Scalable and Modular Architecture for CSS →

This thing is a beast and it would be hard to pull just a few quotes. But...

Throwing every new style you create onto the end of a single file would make finding things more difficult and would be very confusing for anybody else working on the project.

If done right, Modules can easily be moved to different parts of the layout without breaking.

Only include a selector that includes semantics. A span or div holds none. A heading has some. A class defined on an element has plenty.


Does your organization maintain and use a public style guide? Post it!


  1. Before, I used multiple line CSS formatting. After reading one of your old article about CSS formatting I am now a single line CSS man. It is shorter and faster. Also, I think most people come up with their own formatting system.

    • Permalink to comment#

      I am exactly the same way. having a separate line for each property makes it harder to read, in my opinion. But I almost exclusively work outside of a team when it comes to CSS.

    • Rob
      Permalink to comment#

      To modify one of your CSS properties, whether it is applied to a class or ID in your case, you would have to scroll left-right and visually find it against/next-to and back-to-back with others in that single row.

      In a vertical setting, and laid out for example alphabetically, you can find and modify things easier and quicker.

      .class {color: #000000; background: #FFFFFF; font: 1em Arial, Helvetica, san-serif; font-style: italic; height: 150px; width: 500px;}


      .class {
      color: #000000;
      background: #FFFFFF;
      font: 1em Arial, Helvetica, san-serif;
      font-style: italic;
      height: 150px;
      width: 500px;

  2. “I have a blanket-ban on IDs in CSS. There is literally no point in them, and they only ever cause harm.”

    No truer words were ever spoken

    • John
      Permalink to comment#

      Can someone explain this a little better? I’m assuming one would only ever use classes instead of IDs. Is there really no advantage of IDs?

    • From my understanding, it has a quasi-!important effect on elements. If you use #id then you can’t override that elements style unless you reference it with #id again. So to give an example of a use case…

      #nav .logo {}
      .logo {}             /* #nav ignores .logo */
      .nav .logo {}
      .logo {}             /* .nav obeys .logo */

      I think that's correct :|

    • Permalink to comment#

      I think one case you can make for using IDs is that they are supposed to render your css quicker. Chris wrote an article on this on that very subject. I realize that the article is 2 years old but I think it still holds true.

    • FWIW, I totally disagree with that statement. ID has a purpose, and many times specificity is not be a problem, but a solution.

      A blanket-ban on tables has already pushed people to come up with crazy ideas… as using lists in lieu of data tables, so let’s make sure we don’t do the same thing with IDs.

      I already see people using rules like this:

      .someclass .someotherclass .yesanotherclass .canyoubelievethisisanotherclass .andyetonemore {…}

      Autrhors now use classes to increase specificity which decrease performance, create bloated styles sheets, etc.

      There is plenty of goodness in IDs and I think it’s wrong to scare people about their use.

    • John
      Permalink to comment#

      Ok gotcha – I suppose I’ve been somewhat subconscious of that concept without sitting down and really identifying what it did. I’ve always subscribed to the containers were IDs and anything within it was a class and I’ve always just used how IDs overwrote to help me not have to create additional classes

      So like instead of having a specific h2 class for the header, I could define that any h2 within the header were a color that would show up. Maybe that’s bad practice and I had no idea lol.

    • Permalink to comment#

      I have to agree with @Thierry. I think IDs are tremendously useful. I’ve been noticing the “.class .class .class .class .class .class” thing as well and was wondering what that was all about. Didn’t actually realize people were anti-IDs. Can’t say that I see the argument.

    • I’m totally on the “never use ID’s” thing. If you are having a specifity problem, using a selector that infinitely more powerful than a class is a sledgehammer approach when you need a knife (or something, you know what I mean).

    • Chris,

      You’re saying

      “If you are having a specificity problem, using a selector that infinitely more powerful than a class is a sledgehammer approach when you need a knife”

      Does that mean you’re assuming that using IDs is a result of a specificity problem? Because I think this is far from the truth. Many authors use IDs for their semantics – the way it should be used ;-)

      If the styling of an element is meant to be unique, how is using .logo better than #logo? And I’m not saying to use the ID to stuff a rule with all the styling for an element, I’m just saying to use it to introduce unique declarations. Elements with IDs may be styled through a combination of rules (via type, class, id, whatever).

      Also, note that my example uses the word “logo”, but what happens when the name is more generic (as class names should be) and the project is huge? Then authors cannot safely assume that a given rule is specific to a single element. And from there the whole thing breaks loose, because they fear of changing something in that rule, they end up introducing another class – just to make sure they are not messing up with another element somewhere in another page of the site.

      Also, don’t you think that rules like the one below denote a serious specificity problem?

      .class1 .class2 .class3 .class4 .class5 {…}

      I see these all the time, and in my opinion it is no better than “using ID for almost everything”. But the problem has to do with how the tool is used, not with the tool itself.

      You use the “sledgehammer” analogy, so I’ll finish with this one:
      If all you have is a hammer, everything looks like a nail!


    • Permalink to comment#

      I can see what you mean. However, I can still think of instances where referencing content via an ID would be a quick and easy way to target that content and also “organize”, if you will, portions of the page. They are great because they are unique. At least in my experience, they help me feel less overwhelmed, ha!

    • VJ
      Permalink to comment#

      When your automated test scripts e.g. watir-webdriver, ID’s are brilliant for identifying elements on the page.

    • David
      Permalink to comment#

      My opinion would be that IDs and classes both have their places, and both should be used in projects. Some have already mentioned, semantically, #logo is better than .logo

      After all, IDs have a specific purpose, to be used once to identify an element on the page. Classes are used for elements that will appear more than once, for example, you might have a #comment-thread and within that, elements that have a class of .comment-body or something along those lines.

      I see no advantage over using .comment-thread over #comment-thread, and if people are experiencing problems with styling elements inside of this because it’s an ID, I have to question what you are doing, as I never experience such issues.

      Just my opinion ;-)

    • Sean
      Permalink to comment#


      Most of the examples you’ve suggested there are poor development issues rather than confusion over when ID is more of less appropriate than a class.

      For example a developer thinking there is a blanket ban on using tables, even for tabular data, has a deeper misunderstanding of the CSS spec(s) than no coding methodology is going to fix.

      Also, i know you only used it as an example, but something like .class1 .class2 .class3 .class4 .class5 {…} is just taking the use of classes to the nth degree, and a developer who does something like this is probably just as likely to abuse id names for specificity and end up with something like #header div #branding #logo img {…}

    • @Sean,

      It seems you agree with me then. IDs are no problem at all, it is just how people use them.

    • Sean
      Permalink to comment#


      I agree in the sense that classes present their own set of problems, but I never use ID’s for my own code and IMO they force a level of specificity that defeats the purpose of the C in CSS. The only times I use IDs is when I end up in a specificity war with a 3rd plugin that has its own ID’d the max CSS code hidden away inside it that I need to re-style

    • @Sean,

      “IDs force a level of specificity that defeats the purpose of the C in CSS”

      I couldn’t disagree more with this statement. As we all know, the C stands for cascade which involves a lot of things. If we look at the big picture, IDs are not a problem… they are part of the solution.

      If “IDs are bad because they are too specific”, why don’t we avoid using classes whenever possible then?

      Years ago, I thought the best way to go was to avoid using any hook and rely on descendant selectors instead. I was barely using classes, let alone IDs. At the time, I could have argue with anybody that using class was bad because ” they are too specific”.

      Exact same argument I hear today about IDs…

      Anyway, we have “tools” to address a various range of challenges. In my opinion, ignoring some of these tools entirely is not wise.

      We had the same discussion in the past about “!important”. I read many many times “do NOT use !important EVER!”
      Yeah, sure :)

    • Sean
      Permalink to comment#


      i meant 3rd party plugin

    • I can not see the issue with using ID’s in CSS. Have you ever worked on Dot Net applications? These use ID’s for the calls in .vb or c# so I sometimes use these existing ID’s to style. But in your case you would then bloat out the document by passing in classes to then hook up to your CSS file increasing load time? As for aligning my CSS I generally add in the position elements then box model stuff then any text bits and then prefixes-

         float:left; position:relative;
         padding:8px; margin:16px 0 4px;
         background:#f8f8f8; color:#505050;
         -moz-box-shadow:1px 1px 1px rgba(0,0,0,0.8); -webkit-box-shadow:1px 1px 1px rgba(0,0,0,0.8); box-shadow:1px 1px 1px rgba(0,0,0,0.8);

      just like that. I think it keeps everything in its order and makes it easy to read.

    • Sean
      Permalink to comment#


      I order my CSS like that also, usually any positioning type declarations first, then margin/padding, then the rest. It takes me too long to parse the alphabet in my head to order things alphabetically. I have never worked in .net, i understand the use of ID’s there, as well for Javascript, its just for CSS that i’m not down with the IDs unless forced into it

    • Sean
      Permalink to comment#

      @Thierry, well each to their own. I guess the important thing is be consistent, and document our code, so that the next developer can easily understand what is happening when they join the project

    • Permalink to comment#

      I’ve already expressed my beliefs on ID selectors elsewhere

      I don’t mind using #page, #header, #nav, #wrapper, #content, #sidebar, and #footer in my css for sweeping region-specific styles. These styles are tightly coupled to this particular structure, which makes them less reusable; because I reuse the structure, they are reusable. The important thing to remember is that using an ID in a selector is very specific, and should be used sparingly.

    • I’ve just written some in-house CSS rules for developing our app here at Typecast. These rules do advise that IDs should NEVER be used for CSS. I firmly believe that crafting CSS should always focus on re-usability, it should be about creating patterns instead of one-offs. IDs are unique by nature and so work inherently against this. No matter how much you think you’ll only ever use a pattern once, somewhere down the line you’ll find yourself needing it again.

      This approach also suits us because of the heavy amount of Javascript interaction in our app, leaving IDs for the back-end devs to play with helps to reduce conflicts between design and interaction as our app grows and changes (which is something that has caused us issues in the past).

      As a few people have already mentioned though, this kind of decision often depends on the situation and the kind of project you are working on – what may work for us might not for someone else.

      Of course, the next fun part for us is retro-fitting this rule to all the work we’ve already done!

    • It’s really interesting to see this conversation, it’s one of those basic, core things that usually isn’t spoken about, because people are interested in a new technique or property.

      But I’d go on the side of the ID advocates.

      Yes, classes make it really easy to keep reusing the same bit of code, and that’s good. But what if there is an element you know is going to be unique on every page. One that, if it did appear twice on the page, it would be a signal that something was wrong (such as a CMS spitting out strange chunks of code).

      If you use a container to centre your web page, and know you won’t want two <div id="page-container">...</div> elements on your page, because everything should go inside that single container. Then using an ID solidifies this in the code, if there are two of those elements, there might be some sort of visual give away that things aren’t working as expected.

      The same example can be applied to the .logo/#logo point that Thierry made, for most websites, you know that your logo will only be used once on the page, it would look weird otherwise, so if it does end up that two #logo elements are on the page, you know that something has gone wrong when that page was generated.

      It may be different for larger sites, but then as is said at the start of the article, you’ll probably be attacking the styling a bit differently (library, preprocessor, etc.).

      So for small sites, I simply can’t see the problem with doing something with a bit of conviction and saying “I know that there won’t be two logos on the page, let’s commit that to code”.

      Just my view on this debate…

    • Rob
      Permalink to comment#

      The id selector is used to specify a style for a single, unique element.

      The class selector is used to specify a style for a group of elements. Unlike the id selector, the class selector is most often used on several elements.

      body {
      color: pink;
      background: blue;
      #id {
       height: 200px; 
       text-align: center; 
       width: 400px; 
      .class {
       color: #000000; 
       background: #FFFFFF;

      The id in this case could be used to style the logo area or section of the page.

      The class on the other hand, could be used multiple times; for example, on any text that needed to be black and have a background that was white where it would usually be pink.

  3. Permalink to comment#

    Very nice. I always have questions, and I always poke around to learn more and to do things right. It is because of Chris that i code now valid xhtml, and now html5 (I would not know how to miss code this one).

    I have a question though, you said:

    color: #FFF;    /* Okay */
      color: #FE9848; /* Okay */
      color: #fff;    /* Not okay */

    Why is it that #fff is not ok? I did not get it.

    One question I always, I never do this, because I think more code is not good.


    But I always I had a question on this one:


    I do instead:


    Do we do them with the single ‘ or the double ” or do we simple leave it out. I personally do the double.

    • I am interested in hearing why #fff is bad versus #FFF as well. And I do the same thing with my background code (neglecting to include “-image”). However, I do use ‘ ‘ instead of ” “.

    • I think it’s more for keeping the code uniform rather than it being bad. Much like in programming where they say either use camelCase or underscore_it.

      I get annoy when I see #FFF and #fff in the same code, or even #FFFFF, which is needless extra 3 characters.

    • For the record, I could care less about FFF vs fff.

      Not even really about the consistency.

      You don’t “read” hex codes so it just doesn’t matter.

    • Reinier Kaper
      Permalink to comment#

      For ‘#FFF’ vs ‘#fff’ there’s really no issue at all, apart from maybe consistency in your code. We work with both Photoshop and Fireworks at this place so we end up with a lot of variation (PS doesn’t and FW does capitalize hex).

      For single versus double quotes in CSS, I always keep single quotes for one reason: when I need to add/edit CSS in JavaScript/jQuery later, it saves you trouble in escaping your quotes.

      That obviously only goes if you use double quotes for strings in JavaScript (which I do).

      /* nice */
      var some_css = "background: transparent url('/img/sprites.png') 0 0 no-repeat;";


      /* nasty */
      var some_css = "background: transparent url(\"/img/sprites.png\") 0 0 no-repeat;";
    • Rob
      Permalink to comment#

      Colors are displayed combining RED, GREEN, and BLUE light (RGB). The combination of red, green and blue values range from 0 to 255 and gives a total of more than 16 million different colors to play with (256 x 256 x 256).

      Most modern monitors are capable of displaying at least 16384 different colors and with the RGB being used in this example, it is actually referring to RRGGBB – a Hex value written as 3 double digit numbers, starting with a # sign. The more digit numbers/letters used, the more specific you can be with your color pallet.

      Colors in CSS can be specified by the following methods: Hexadecimal, RGB, RGBA , HSL , HSLA or Predefined/Cross-browser color names (red, pink etc.)

      In terms of capitalization, W3C, Photoshop, Colorzilla, Kuler etc. usually use uppercase formatting, similar to how the Unicode is written. It does not affect how the color is interpreted and merely comes down to aesthetics and compression.

      Your background problem is a long vs. shorthand property declaration issue. If you were to use a pattern that repeated for example, another CSS rule would need to apply.

      Here is an example of the font property:

      #ID {
      font-family: Arial, Helvetica, san-serif;
      font-style: italic;
      font-size: 1em;
      color: #000000;

      Which can also be written like this:

      #ID {
      font: 1em italic Arial, Helvetica, san-serif #000000; 


      As per W3C’s recommendations, URI values (Uniform Resource Identifiers, which include URLs, URNs, etc) are formatted with a value url (‘ followed by optional white space followed by an optional single quote (‘) or double quote (“) character followed by the URI itself, followed by an optional single quote (‘) or double quote (“) character followed by optional white space followed by ‘). Using either or none is fine, however, the two quote characters must be the same.

      body { background: url("") }
      li { list-style: url( disc }
    • @Karl and Jonathan Graft. One reason NOT to use

      background: url('something.png');

      instead of

      background-image: url('something.png');

      is that “background” defines all of the different options for backgrounds, including background-image and background-color, even if you don’t specify them. I don’t remember if this will work:

      background: url('something.png');
      background-color: #fff;

      but I know for sure this won’t:

      background-color: #fff;
      background: url('something.png');

      In the second case, the “background” statement will override the “background-color” statement. I almost always type them out separately if I’m using both an image and a color for the background on a given element. Or even if I’m not, I usually type them that way in case in the future I need to add one or the other. Might seem overly cautious, but that’s my opinion anyway.

  4. I have two points I feel strongly about…

    1) CSS rules go on one line. Why? we all use widescreen monitors and we don’t use them in portrait mode, so why would we not use more of the horizontal space available to us so we can see more of our CSS on one page?

    When I see really long stylesheets that only use a few inches of horizontal space and you can only see a few rules on screen at a time it drives me crazy.

    2) I much prefer this …. {width:80px; height:80px;} to this… {width : 80px; height : 80px;}

    I know it doesn’t relaly look very different here but it does in a monospaced IDE. Leaving spaces before and after the : means that there is no visual grouping between property and value. The 80px “belongs” to the width property so should be grouped with it and seperated from the height property. It just makes it much easier to read and find properties quickly.

    I also agree with not using IDs. I’ve stopped using them and I get less specificity headaches.

    • If you’re in a version control environment, one-line CSS goes right out the door since it makes difs useless. That combined with CSS3 vendor prefix stuff, and I’m firmly back in “multi line” CSS camp. I used to have your exact same sentiments though so I feel you.

    • John
      Permalink to comment#

      I found that mult line CSS ended up being more courteous to the people that I developed with.

      I tried to go single line, and in some cases I’ll make it a single line (if I’m defining only 1 or 2 attributes and it’ll never be more than that).

      But I found it was frustrating that everyone had different ways of working and it would wrap differently. Working in multi line made sure everyone saw the same thing.

    • joehouin
      Permalink to comment#

      I like the idea of single line to fit more in but it’s impractical. As web developers/designers we often worry about how long a line of text will be on out finished product so it’s easily read by the user. Why then would you want to force yourself to read lines that stretch the full width of a 20″+ monitor? Not to mention it’s not like text in an article where you can sort of maintain your place using context clues and knowing what you just read.

      .class1{height:10px; width:20px; border: 1px solid #ccc; display:block; float:left}
      .class2{height:20px; width:20px; border: 1px solid #eee; display:block; float:left}
      .class3{height:20px; width:20px; border: 1px solid #ccc; display:none; float:right}
      .class4{height:10px; width:10px; border: 1px solid #ccc; display:block; float:left}

      This is a pain to read (made easier by the formating on the comment system here) and that’s only like 60-70 characters across.

  5. Permalink to comment#

    I love the GitHub Style Guide :) I believe it was the first one I jumped into when I started getting serious about CSS.

    • I like it, the only thing that truly bothers me is using 2 spaces instead of an indent. Probably just personal preference.

    • Permalink to comment#

      I completely agree! My coding style is tab for indent, always has, always will.

    • Interesting that they chose 2 spaces. I recently moved from hard-tabbing to soft-tabbing in because I found it worked better across different platforms and editors (a space is a space where’s tabs can be odd). But I use 4 spaces that is typically equal to a tab.

      But I find that 2 spaces is a bit messy, looks like somebody accidentally pressed the space bar more then they ment too :\

    • Two spaces seems odd to me too, I was just reading up on these to see what other people said, I realize the thread is two years old. Tab is one button that reliably produces the same amount of space every time, whereas using actual spaces leaves a lot more room for error/messiness — the preference for spaces doesn’t make sense to me. Plus you can tab-in large blocks with Notepad++/ Textwrangler/Dreamweaver, too, which means it’s easy to backtrack and organize things you forgot to space while you were pounding away on some last minute styles.

      But I guess maybe the spacing requirement comes from situations where tabs are problematic? Seems like the best thing might be to set “tab” to generate spaces (rather than tabs) in the editor of choice. Endlessly pressing the space bar drives me crazy, but I also don’t like when things aren’t lined up neatly, so not having a one button space would be really annoying.

  6. Possibly the most amazingly helpful post at the right time. I’m currently looking at writing a style guide and needed some reference points.

    Luckily I agree with the majority of the points each author has mentioned though

    I have a blanket-ban on IDs in CSS. There is literally no point in them, and they only ever cause harm.

    In the vastness of cases, yes, but for high-up layout options IDs aren’t a bad thing IMHO. Thinking #header and #footer here would be fine as they are unique components of the page. But I understand what Harry is getting at.

    But so far reading through I haven’t seen much mention of using short-hand code, such as background or padding rather than background-color or padding-left padding-right in the cases of only use the long term for specificity and use short for most other cases. (Something to add to mine!).

    I would like to see more mention of CSS/LESS/SASS documentation tools; is it that KSS is the only real option out there at the moment or is automated documentation not that popular? Personally I see it being a pretty awesome tool to build a straight-up document on each version of a site style to understand what is style is being called where. (I know you could just look at the CSS files but larger sites this would be most handy).

  7. WordPress also has their own brief CSS style guide:

    • Oh dang I forgot about that. I found their latest version though (not the codex one) and included it in the article.

    • Thanks for including the WordPress one from the handbook – I’ve now wiped out the Codex (wiki) page to point to that page instead. Doesn’t seem to make sense to try to maintain ever-evolving standards in two places :)

  8. Even if I understand why IDs can be nefast, I don’t think they have to be bannished. They can be very useful, just not under every circonstancies.

    Great round up anyway Chris, good to see such good advises about CSS. I especially like the one from Nicolas Gallagher.

  9. Permalink to comment#

    “Use ID and class names that are as short as possible but as long as necessary.” When you work in a team environment this is super important. Too short and its meaningless too long and its annoying.

    • Permalink to comment#

      Couldn’t agree more Dave. Human beings read style sheets too! Let’s hope and pray for a day when naming conventions are also appreciated.

  10. Do any of those style guides include a set order for listing properties? The most annoying aspect of working on someone else’s style sheets is the erratic and inconsistent placement of properties.

    • Sean
      Permalink to comment#

      The Google Styleguide recommends alphabetically ordered declarations, i haven’t read through all the others yet

    • joehouin
      Permalink to comment#

      my personal pref is type – > alphabetically. By type i mean I sort of categorize properties into

      Layout: within the page like (display, float, etc)
      Form : width, height, etc
      Style: border, margin, paddding, etc
      text: font-size, font-family, etc

      And alphabetize within those groups. Although now a days I’m trying to get more into OOCSS so I’ve been breaking those out into separate classes for reusability.

  11. Permalink to comment#

    These types of posts are always interesting. It’s always good to know how other people code just to check if you can do anything better.

  12. Adrian Salgado
    Permalink to comment#

    You missed Starbucks Style Guide btw.

  13. Hawidu CSS’s Syntax Guide guides the project. Folks might really hate the style it uses, but it’s great to me.

    The idea behind the Hawidu CSS framework is that a [working] project would be a single file that is as close to minified as possible while still being readable. Projects in this style avoid the cascade, use attributes other than class/id for styling when reasonable, and only paste in the fanciness when needed.

  14. Vytenis
    Permalink to comment#

    Great reference. As I’m new to web and currently teaching myself, it’s great to have several different ideas to rummage through to not only see how other people do something but to see what I would do and compare. Thanks. Would be great to see this updated and expanded.

  15. Permalink to comment#

    I think this one is a little older, but probably still good:

    And it covers more than just CSS. And then there’s this list on gimmebar:

    I can’t remember who put that together, though… Anyone know? Again, probably more than just CSS, but certainly relevant to this post.

  16. jimbo
    Permalink to comment#

    so what is the deal with quotes in image references?

    .class { /* Correct usage of quotes */
    background-image: url(“images/bg.png”);
    font-family: “Helvetica Neue”, sans-serif;

    /* Recommended */
    @import url(//;

    html {
    font-family: ‘open sans’, arial, sans-serif;

    just house style?

    • Image quotes are optional. Font family names with spaces require quotes; single or double – it doesn’t matter

  17. Permalink to comment#

    Helpful information. Thanks for sharing.

  18. I’m not sure about only using hyphens to separate words in your selectors. For example, when using an OOCSS approach, I feel there is a need to separate the module, its variations, its components, etc, by naming conventions. For example…

    .link-list { }
    .link-list_item { }

    Here, I’m using an underscore to indicate that the “link-list_item” element is a component, or piece, that makes up a “link-list.”

    Basically, I think this actually improves comprehension of the CSS over everything just being hyphens. It’s easy to tell what the element hierarchy is based on the naming convention, and this has more benefits than detriments.

  19. I understand why you wouldn’t want to use ID’s but the trouble with blanket statements from experts that they should never be used perhaps needs qualifying. There’s a bit of an ID witch hunt at present and I’m unconvinced it’s entirely workable in the real world.

    For example, IMHO, there are times when using an ID as a selector makes the most practical sense (I’m thinking of when working with a CMS with no practical means of altering markup). I also don’t mind using them to set things I know will never change (e.g base styles such as #sidebar in a design).

    In conclusion, I would say using classes is preferable and ‘best practice’ and one should understand the implications of using IDs as selectors but don’t fear that the world will end if the odd thing is styled that way. There’s often far bigger fish to fry!

    • Permalink to comment#

      Ben, you said:

      there are times when using an ID as a selector makes the most practical sense (I’m thinking of when working with a CMS with no practical means of altering markup)

      Maybe I’m wrong, but my initial reaction to this is that if the CMS has no practical way of altering the markup and it adds IDs to those untouchable elements, and not classes, then that sounds like a really bad CMS. Generally, CMS’s add classes (like WordPress does), not IDs, or else in addition to IDs.

      Do you know of a CMS that only adds IDs and doesn’t let you change the markup? I don’t have enough experience with different CMSs but that doesn’t sound like it would happen very often, if ever.

    • Hi Louis, in principal I totally agree but sometimes it’s easy to cast things in a bad light based on ivory tower idealism. I’ve had plenty of instances working with organisations that have their own (limited) CMS system.

      The whole world doesn’t run on up to date CMS (or even open source) systems and there are many clients and institutions running legacy systems that don’t give you control over particular areas of the markup.

      However, even if you could (use a class instead of ID) I still don’t think opting for an ID instead necessarily constitutes a cardinal sin of writing CSS. Like everything else relating to the web, I’m going to resort to the ‘it depends’ cliche.

  20. Permalink to comment#

    Harry Roberts also has this:

    But I have no idea how similar/different that one is from the one you link to in the post…?

  21. Permalink to comment#

    Lead frontEnd dev…

    Using a bit from the post +:

    When staging JavaScript events with CSS(:target – onclick, :hover, :focus (preferably with transitions of course), declare these blocks in new, well-doc’d sections with an obvious reference comment in the base section/block. Considering that ID blocks r mostly unnecessary, reserve them for fine-tunings IF @all necessary. Along with this method:

    Construct your HTML/CSS in such a way that allows you to build your CSS sections to mimic JavaScript Singletons, and your CSS blocks as subclasses – meaning: get your CSS to look aw much like JSON(a universally understood pattern) as possible. This includes SEEMINGLY unnecessary iterations of parent classes in order to keep your code more semantic/slef-doc’ing.

    E.G.: .parent .child .babyClass{}. OR: .parent .child, .parent .sibling{}. NOT: .babyClass{} or .sibling{}.

    Do as much GUI design as possible in CSS(judgement call :-/), and try to reserve javaScript for just DOUI(pronounced: Dough-EE: Data-Oriented UI). This separates logic processing from graphical presentation, but u can always use JavaScript to override your CSS.

    Very crucial: using CSS :before/:after with the content attribute can save you from doubling an event b/w CSS and JavaScript just to add a graphical change(CSS) and a text(not html) change(using JavaScript innerHTML).

    Also, its ‘!important’ to know when ur wrong.

  22. “If the value of the width or height is 0, do not specify units.”
    This sentence, I agree with you.

  23. Jonathan [JCM]
    Permalink to comment#

    You forgot to put the link to the Google style guide.

  24. Joeri
    Permalink to comment#

    This is some amazing stuff. I’m looking into GitHub’s right now, and it’s got some very good guidelines. I especially like the way they explain their form styling. I’ve had trouble crafting proper, structured stylesheets forever.

  25. Permalink to comment#

    I agree, who cares about FFF or fff.

  26. Permalink to comment#

    In reference to all the mojo about classes over Id’s…. I was always taught to use classes when an element needs to be used more than once, for everything else like #wrappers and #headers I use ID’s. There are instances, actually just the other day when I needed to override a certain element and couldnt because I was using an ID on top of that element. Are these the use cases where we should just bite the bullet and change that ID to a Class? BTW great article, it definitely sparked some convo.

  27. Thanks for the collection, i knew 1 or 2 of them but really thanks for this :)

  28. Test.

    • Was just testing what would happen if you submitted a comment with inline styles as they show up in the comment ‘preview’. They get stripped out when submitted :)

    • Permalink to comment#

      Its the Php strip_tags() function that removed stuff like that I believe. Hekps prevent people from executing scripts on your page. You’d be surprised at what creative things people do with Javascript.

  29. The only thing I mis is a perfect formed example.
    Just give us the best practice of CSS-coding. Like this:

       color: #fed;
       font-size: 20px;

    Also… what is better?




    And why?

  30. Permalink to comment#

    I definitely agree on the update log as suggested. I have come across too many companies (as software consultant ) where there’s no update logs and no way to figure out how they handle change management. by the way – IDs are also supposed to render quicker css. .

  31. Permalink to comment#

    actually ids and class there is different role my concept is clear in the online css editing in mozilla

  32. I agree with at least one statement of all of them. One I don’t agree with is the “one-liner css statement”. It’s not readable at all, and only makes your file code broad. Writing every CSS statement in theoretical sections would clear things up for box-model, pure styling (font, color), and special FX (border-radius, gradient). This would make it easier on yourself and also on everyone who’s gonna touch the stylesheet after you.

  33. I don’t think this has been covered but #id’s are very useful as hooks for your Javascript functions. It’s a lot better than using .classes and having to navigate the dom using unwieldy selectors. Having a blanket ban is not necessary but it is important to use them in the right places.

  34. Did somewhat the same as Harry does for my coding-guidelines in HTML and CSS.

    I love the idea of having a good code style-guide and stick to it. This is what happens with JavaScript and other programming languages since years and finally it comes to HTML and CSS. Awesome.

  35. Permalink to comment#

    And here is my follow-up guideline (inspired by Harry and Hans I wrote down my style): My coding style and guidlines.

  36. Permalink to comment#

    The CSS Wizardry article is terrible, I can’t even start to explain why you should use ID’s in your webpage! Just dont refer to them in your CSS. Neglecting to add them at all is really bad practice as it doesn’t allow developers to interact with elements easily.

    The general rule of thumb is that you use ID’s on unique elements and classes on re-usable elements. A step better than this is to assign ID’s to all unique elements but style them with a class. (Basically, no styling on ID elements)

    • David
      Permalink to comment#

      So basically, bloat your HTML with IDs that you aren’t using?

      It seems everyone has different opinions (Which we’re all entitled too), but I still can’t understand why people are hating on IDs. If you’re having issues with them overwriting something down the line, you’re probably not approaching it from the right direction perhaps? No one can really say without seeing some examples of the issues.

      IDs help render CSS faster as already stated, they are great for JavaScript (when selecting elements), as they are more efficient than class selection. They should only be used on unique elements (Like they were pre-HTML5, IDs of header, footer etc).

      You also mentioned “by general rule of thumb” about IDs being on unique items and classes on reusable, slap me if I’m wrong, but I’m pretty sure that’s how it is meant to be (Valid HTML ‘n’ all …).

      That’s my opinion again ;-)

  37. Some of the presented rules don’t work for me.
    I’ll stick to the official recommendations from WHTWG and W3C CSS WG.

  38. Stevie D
    Permalink to comment#

    Well that was fun. I spent ages carefully crafting a well-argued response, tried to submit it and was rudely told that the name and email fields needed to be completed. How about some kind of warning before I hit ‘submit’? And then how about some way of remedying my mistake rather than making me click the ‘back’ button and retyping it all?

    Sorry, but I’m not going to waste my time typing it all out again, so you’ve missed out on my words of wisdom. Your loss.

  39. orange county web designer
    Permalink to comment#

    Great tips here. Utilizing these methods makes recreating a stylesheet much more efficient.

  40. A few days late to this conversation, but I have built and maintain a Styleguide/pattern library framework.

    Concepts are simple, use the framework to build your own pattern library and leverage the pre-designed views for the rapid development of the styleguide.

    Be warned, it’s in it’s alpha stage and rapid development itself. But there are great ideas to be taken away from it if you are interested.

  41. Greg Hemphill
    Permalink to comment#

    To use or not use ID selectors in CSS. 

    I think a big point is missing from the conversation I’ve seen on the ID selector topic: Code Reuse.

    By definition an ID is used on one and only one element on a web page; this is dimametrecally opposed to code reuse. 

    By using well thought out classes and reusable components you are able to make sites with a smaller CSS code base, more consistency in appearance, easier to maintain and debug, and it becomes faster to create new pages. 

    In the programing world there is a concept called DRY (Don’t Repeat Yourself). A simple example would be calculating a total on an ecommerce site; you might have many pages or side bars where it’s displayed. It should be abstracted to a common function all these places call in order to calculate a total. Thus if something comes up, like a change in the way tax is calculated, you make the change in one place and it applies to them all with a greatly minimized risk of missing one or having a typo in just one that goes unnoticed. This sort of code reuse can be accomplished in CSS by using well thought out classes; it makes life easier.

    The thing is, there isn’t much of a case for using IDs in CSS. If selector strength is your reason, then you have a larger problem of overly aggressive selectors somewhere else in your CSS; this is a band-aid use case.

    IDs do have a useful purpose on a web page, but their primary usefulness is in JavaScript. Being able to identify a unique asset in a list of similar assets. For example, you might want to know exactly which thumb nail image a user clicked on before displaying a larger version of the image in a light box. Their usefulness is fading with the advent of HTML5 data-something attributes, but it’s been a valuable tool for individualizing items. 

    So my two cents is: if you are using #logo in your CSS, you should be able to use .logo instead. If you can not, it’s a red flag you’ve not thought out other parts of your CSS well enough.

    • David
      Permalink to comment#

      You say it’s been missed out from this conversation, and yet one of the main topics have been specificity (which means making an object too specific that it can’t be used elsewhere, which is the same as code reuse).

      I’ve said it before, and I’ll say it again, why use .logo over #logo? You don’t save any space in CSS, because you’re still having to style it exactly as you would do with an ID. It’s understandable if a logo appears more than once, but most often it does not. Therefore code reuse does not apply in these cases, as you don’t write a function for something you only do once in programming (such as logging out, it may be on multiple places on a site, but it often goes to the same place, so no need for a function).

      By using a class over an ID in cases where there is no need (Or the believed need of IDs being pointless because of specificity and code reuse when that doesn’t actually apply), it has already been stated that classes on CSS aren’t as efficient as IDs, and the same applies for when using JS to select elements.

      So in short: for single use cases (such as most logos, holders etc), you don’t lose anything by using an ID (Nope, not even code reuse), but you do gain slight performance boosts (which can add up!).

  42. Is this a custom post type ?

  43. Also, would be useful to add to the list of BEM:

  44. AntoxaGray
    Permalink to comment#

    I do not agree with:

    If the value of the width or height is 0, do not specify units.

    I always write this:


    Why? Because of Chrome Web Inspector, I can use up/down arrow keys if I have px, but it will not automatically add ‘px’ if I have only 0, so it will not move element. Same for margins, paddings.

  45. Permalink to comment#

    This is a great collection of thoughts and methods!

    A long time ago, I thought long and hard about declaration order (probably more so than what would be considered “healthy”). Instead of arriving at alphabetical order, which is pretty logical, I came up with the idea of writing declarations in a hierarchical order.

    Declarations describing things like position, stack order and the objects affect on other objects came first, followed by the objects dimension, border, padding and background display. From there I would write any properties that dealt with content inside of the object such as font family or color. This allowed me to think about the object behavior from a global to specific context.

    It works on paper… sometimes.

  46. Permalink to comment#

    According to Paul Irish’s post on HTML5Rocks about How Browser Works he mentioned that CSS Rendering is done from right to left. For each element everytime CSS Engine go through whole stylesheet to look for specified element, once it finds the element (via id, class, tag or universal selector) it moves to its left selector and checks for the parent if the parent is right then move ahead and so the styles are applied. I wrote a blogpost on it explaining the whole process.

    So this proves that if there are no levels of nesting then it will improve performance of page which can be helpful in complex apps. E.g. If you look at GMail’s CSS you will find no nesting levels. Each classes and ids are unique in whole app. Even though they are machine generated (I don’t know how).

    This takes us to GitHub’s and Google Code Guidelines of specificity and naming convention. Google suggests

    “Use ID and class names that are as short as possible but as long as necessary”

    while GitHub encourages Specificity. This arises a question how naming convention should be done to achieve both guidelines? Is Smurf Naming is ideal way here e.g.

    .container-preview { ... }
    instead of something like
    .container .left-container .preview { ... }

    however by doing Smurf Naming it will generate meaningful but really long names which eventually will become annoying. Is there any other way to overcome this problem?

    PS Can some one tell me how GMail generates those CSS?

  47. Kevin L.
    Permalink to comment#

    I think the solution to the issue has been solved for some time now by SASS a long time ago.

    If you have some people who prefer to do their work in x format but want the general format at the end of the day to be y, you can make sass import whatever format they prefer and have the actual production stylesheet to be formatted a variety of ways, such as compressed, single-line, whatever.

    Even better, it’ll just convert what already exists to a different format if that person leaves in milliseconds.

    That way, styleguides can be adhered to without a worker or anyone really having to worry about changing the way they read or create the stylesheets which ultimately wastes time that could otherwise be used to work on what really matters most: The site styled and performing in a way that maximizes its purpose for users.

  48. Tim
    Permalink to comment#

    I don’t really care about IDs or classes. In my opinion there should be only one type of style and everything should have it’s own unique name. But that is not how W3C set things up. Now they created even more elements (header, nav, footer, etc). These elements have the exact same weight on a page as html and body. In my opinion that is not good or right. Not every page on the internet has a header or footer or even a nav. There can be standalone landing pages. However, every page on the internet has a body contained within html.
    Therefore, everything else on the page should be a “class” (which doesn’t necessarily mean the current CSS class definition), but just a style that is declared. And everything on the page should have it’s own unique name for a style, though it can be reused wherever you want. Right now, you can have a style like #nav .nav. You shouldn’t be able to do that.
    I don’t think ID’s or Classes make things easier. They are just more confusing and adding to it with things like header and footer makes it even moreso.
    W3C (and humans in general) make things too complex. Everyone has been about simplifying pages year over year, but then these weird random new elements keep being added to make things more complex.

This comment thread is closed. If you have important information to share, you can always contact me.

*May or may not contain any actual "CSS" or "Tricks".