Grow your CSS skills. Land your dream job.

Judging CSS / Spotting Bad Code

Published by Chris Coyier

In a recent Q&A article on Smashing Magazine, a question was asked about how to tell if a developer has written bad CSS. Specifically:

What are the signs that the CSS is sub-optimal, or that the developer hasn’t done a good job? What do you look for in CSS to determine how good or bad it is?

I thought that was an interesting question and I'd expound upon my answer a bit.


Why?

Perhaps you've hired someone to write CSS for you and you want to have a gauge of how good they did. Perhaps you're looking through someone's CSS that you may potentially hire. Perhaps you want to gauge your own CSS somehow.

The Obvious Test

Look at the website. If it looks all messed up, then they did a bad job.

Taking that a step further, check it against the browsers you agreed on would be supported. The design should be workable in all of them.

If the design is supposed to be responsive, resize your browser window to ensure the design works no matter what width or height it is.

If everything looks good, that's a good (and required) first step. But it's not absolute proof the CSS is good.

The Formatting Test

Take a look through the authored CSS file. Remember that it's best practice to serve the live website minified CSS (all non-important whitespace removed), so don't look at that.


That's not intended to be read by humans. Look at the file that they actually created.

If you have an established style guide that was expected to be followed, was it followed?

If not, does it look consistent - as if they had a style guide of their own that they adhere to? Or is it a bit sloppy? Sloppy meaning sometimes there is one space after selectors and sometimes there is none. Some blocks of code are indented and others aren't. Single line CSS is mixed with multi-line CSS with no rhyme or reason.

Clean code is the sign of a respectful developer. One who has a respect for the craft and the work they do.


From Nicolas Gallagher's Idomatic CSS

If these first two test pass, that's great. But still not quite proof the CSS is good.

The Selector Test

Those first two tests could be done by just about anybody, but from here out you'll need to have familiarity with CSS yourself. Start reading the CSS and see if what you're seeing makes sense to you.

Do the selectors look rational? If you see a selector like

.article #comments ul > li > a.button {
  /* Crazy town */
}

I'd worry. That is a developer fighting themselves with specificity problems, something good CSS doesn't do.

How are the class names? Understandable? Hopefully you don't find anything like "bigGray" or "left50" as the accuracy of those will be surely be short lived making for confusing future development.

How repetitive is it? For example, if you see the exact same box-shadow applied in 20 disparate places that's probably a sign of lack of refactoring. Good CSS developers sense patterns like that and accomodate them better.

The Size Test

How is the file size of the deployed CSS? 100k would be absolutely enormous for a CSS file. Small is good. Even (especially) on complex sites. Huge files is often a sign of lack of consistency.

The Editing Test

Come up with a style you'd like to change on the site and attempt to change it yourself. For instance, swap the all the fonts in use with other fonts. Were you able to familiarize yourself with the code quickly? Did it feel like there was a plan for how fonts were handled in place? How quickly were you able to do it? Faster or slower than that kind of thing normally takes you?

How do you do it?

Have you ever been in the position to judge other's CSS? Did you use similar tests? Did you have more defined metrics?

Comments

  1. David
    Permalink to comment#

    Another thing I look at specifically relates to boilerplates.
    Using something like the html5 boilerplate has become fairly popular in development, and I always look to see; did they just plop their hand-crafted CSS in the boilerplate css file and ignore what was there? Or (what you hope for) did they actually look over the boilerplate and remove that which they might not actually need for their project. Seeing empty media query statements makes me sad.
    On a similar note, if there’s a set print styles in their CSS, print preview the page and check if its actually going to look alright when it prints (default html5bp don’t for every project).

  2. I think this is a great starter list for judging the quality of CSS. I think another big issue out there is repeating style statements (that just conflict each other) and CSS with no comments.

    One thing about the selectors though… you said “That is a developer fighting themselves with specificity problems, something good CSS doesn’t do.” I agree but we aren’t always working with pristine HTML that we wrote. So often we are working to change styles for existing applications, tools, add ons, plugins, etc. etc. Very specific selectors can be a sign of a CSS coder who knows how to work around a tool’s limitations without adding scripts and hacking apart the HTML. It can also be a sign of a CSS coder who isn’t overusing classes and IDs in the HTML and is instead making use of semantic HTML to target items.

    • Permalink to comment#

      Agreed 100%. Furthermore, time is also a HUGE factor. For my personal code I am much stricter than at work simply because the clients generally don’t care about well written code. They would rather the fastest sloppiest code possible as long as we get it out the door in record time. And they don’t care at all about making it easy to update later.

    • Just curious…if/when you compress your CSS, do you remove the comments? I never comment my CSS because of compressing the file.

    • Compression tools can remove comments, here is an example of one: http://www.cssdrive.com/index.php/main/csscompressor

      I always comment my CSS, no matter what. Sometimes even down to the declaration level so the client knows that this exact property is what is setting their background, etc. It depends on the project. I also work with a product that uses nearly 50 CSS files OOTB, so commenting is essential for my CSS file that I have to add on top.

  3. Apart from the items you listed already, consistency is one of the main things i look for in code. If someone is consistent, there is a much higher chance they know what they are doing.

  4. Permalink to comment#

    One of the first things I look for is overly verbose code. For example:

    p{
       margin-top:10px;
       margin-bottom:10px;
       margin-left:auto;
       margin-right:auto;
    }
    

    instead of the much nicer:

    p{
        margin:10px auto;
    }
    

    or

    .cta{
       background-url('background.jpg');
       background-position:10px 10px;
       background-repeat:no-repeat;
       background-color:#FFFFFF;
    }
    

    instead of

    .cta{
    background:url('background.jpg') 10px 10px no-repeat #FFF;
    }
    

    And finally another big one is if they use short hex colors when possible, for example #FFF instead of #FFFFFF.

    Finally, on a painfully funny note is a few years ago I used to work for an agency who had Research in Motion as a client. Their main stylesheet at the time was 700kb large and we had to include it on any page we worked with and ensure our CSS didn’t conflict with any of it.

    • I agree that overly verbose code is bad… but if you are overriding existing overly verbose CSS that you have no control over you need to stick with the overly verbose stuff. Just a clarification for the newer folks posting to this article (which is awesome to see). “Background-url” has more weight than the shorthand “background”.

    • @ Heather (and more important people who read her comment)
      Following that logic: div{background-color: #FF0000;background: #FFFFFF;} would give a red background. But apart from some strange bugs I found in some cases this div will absolutely be white(luckily, because a red background is ugly)

      @ Ryan
      You first write:
      background:url(‘background.jpg’) 10px 10px no-repeat #FFF;
      And then you say you don’t like people writing short hex codes. Funny, isn’t it?

      Personally I prefer to write short hand code but someone writing margin-top etc isn’t a deal breaker at all. Some things are more personal than actual bad or good coding practices.

    • Rob W
      Permalink to comment#

      @Ryan background-url does not exist. I hope that you meant to write background-image: url("background.png");.

    • I always type full hex colors because I’m OCD. Most of the ones I use can’t be shortened, I like uniformity so #FFFFFF looks better and makes more sense to me. Just my personal preference though ;)

    • Not sure I agree with saying you should always use the shorthand declarations. Firstly it makes it harder to read. Also, its not relevant to websites, but most email clients ignore the shorthand and require you to use the full declarations.

      I don’t think you can judge how good someone is at writing css based on their use of shorthand coding techniques. Its like saying talking in slang is better than full english. Its not. Its just personal preference. Its will save a fraction of kb in file size. I think if you need to worry about full declaration bloating the size of you css file you may have bigger issues to worry about.

    • Well, shorthand has it’s convenient sides like: being able to put it in one declaration (and thus using less bytes AND being comfortable with the whole encompassing aspect of CSS) of course, opinions may differ but, I think in the first place that is the reason why we have shorthand css. Next to that, if you have an encompassing css rule (as a base) you can still be more precise down the line to only change certain aspects of a css line. (ie if u use the shorthand background property, you can specify, further down the line, another colour, another backjground picture, another position, etc, while keeping the foundation earlier on in the project). Then again, that is also part of the personal preference. It’s all about the tactics you use on a certain project.

  5. One of the first things I look for: forget inherit, or obviate it.
    Some people forget, and have classes within classes declaring a thousand times the same properties.
    And then, I look absurd and unnecessary repetition of properties. This also related to the abuse of !important already mentioned.

  6. personal projects:
    you can spend plenty of time making super neat css

    agency, client web:
    1.) time is of the essence, it works, ok, deadline met
    2.) you get to work with terrible css you cannot alter, also fun
    3.) other cases or the above combined

    so seeing bad css in client work does not mean always that the css guy is not good (just has no choice)

    • Alan
      Permalink to comment#

      That’s sums up a lot of it. Unfortunately there are times where going through the code with a fine-toothed comb or taking time to account for everything just isn’t possible.

    • Marc
      Permalink to comment#

      Yep pretty much a daily occurrence here. On my own projects I try and keep my CSS files clean and organized (at least on my newer projects haha) but at work I can rarely afford that luxury. I am constantly working with CSS files that are managed by a multitude of people, good luck keeping that organized all the commenting in the world can’t save that…

    • Agree with #2. I’ve done a lot of client work where I have stepped in after the previous developer got the axe or even just hired to do a specific customization. In this case I’ve tried to do my best to modify the code and keep it as clean a possible. Most of time with freelance work you are not hired to clean up the CSS or the HTML for that matter and it’s hard to justify me spending my free time cleaning up the code unless its truly bad and messes up what I am trying to do.

      However, with #1, I do think it’s not always just do it as quickly as possible. If I want to retain the client then I need to make sure my CSS is going to be scalable for future projects. I’ve written some bad code, then the next year the client hires me to update the project and I’m like “who wrote this garbage!” Until I realize I did it.

  7. Superb insight in managing CSS Chris. I always make sure to compress the stylesheet before deploying the site to its live state.

  8. murph
    Permalink to comment#

    Thanks for this article, which is really useful (and the comments too), for someone relatively new to css coding like me!

    Can anyone recommend a good article anywhere on useful ways to organise my css (i.e. wether to group classes all together or not and wether to divide it up in terms of colouring/typography etc). Getting my css well organised is something Im struggling with!
    Thanks

    • David
      Permalink to comment#

      Nicolas Gallagher’s Idomatic CSS :
      github.com/necolas/idiomatic-css

    • Eloise
      Permalink to comment#

      Although you can find tips on organisation, I’d suggest you try to develop your own. Either or those would work well, or in combination together. I personally dislike the colour/typography type grouping but that’s because it’s not how I mentally organise it rather than it being wrong.

      Like all code, organising it to be easy to find your way around, and hopefully for the next person to do the same too is more important, unless you work for someone big enough to say “stuff inefficiency, everyone is doing it this way, all the time.”

  9. Permalink to comment#

    Embedded fonts and images are becoming more common to reduce HTTP requests on page load. They substantially add to the file size of the style sheet and deceivingly make it appear as if the developer is inconsistent or naive. So keep that in mind if judging by the size of a CSS file. (Yes, yes, they should be ported into perhaps a different file; it really all just depends.)

  10. Agreed with you. There should be consistency of what the designer is following for the rules.

  11. Judging CSS usually starts with looking at the production files. Are there definitive sections to help any other developers working on your project figure out your code.

    For example I typically start a style sheet with a key followed by headers defining the following sections:

    
    /*-------------------------------------------------------------------
    Project Name: Example
    Client: Example
    ------------------------------------------------------------------------
    1. Global Styles
    2. Structural Styles
    3. Ect.
    -------------------------------------------------------------------*/
    
    
    
    /*===========================
    1. GLOBAL STYLE
    ===========================*/
    Input global style here
    
    • The Key idea is cool if that works for you. I’m not sure I would personally add or subtract any points for it.

      I’d disagree with:

      Judging CSS usually starts with looking at the production files.

      production files = compressed output not meant for humans to look at.

    • I do similar stuff
      where in CSS it says what it contains or not
      so I can copy/paste/search for it as I have commented each section

      STYLE.CSS contains:
      http://krsiak.cz/style.1.1.0.css

    • Alex Taylor
      Permalink to comment#

      I am using a table of Contents in my style sheets now, but I don’t number the nodes to make it easier to insert something later without renumbering. I make sure that the TOC uses identical text to the section header comment to make it easy to jump to that text with search (for example, ⌘-I in Sublime or ⌃-S in TM).

    • Tommy
      Permalink to comment#

      @ Chris – While Connor didn’t mention it in his reply, I think he might be onto something by checking the production code first. Not to find how it is structured, but rather to prove your main production point: that the files should be minified and un-readable. If they are not, this should be red flag #1.

    • Joe
      Permalink to comment#

      I add a color key at the top.

    • I also use colors in the main stylesheet (MASTER.CSS)

      #000; black (body, text, menu)
      #333; gray  (dark - menu hover)
      #666; gray  (text, border)
      #999; gray  (table border)
            
      #CCC; gray  (background)
      #EEE; gray  (light - menu, background)
      #FFF; white (background, text, text shadow)
      
      #0645AD; blue  (links)
      #98C22A; green (slider button)
      #AECA20; green (slider button:hover)
      #F9F9F9; gray  (bg color in jQuery)
      #C4ED68; green (.highlight border)
      #E2FF9E; green (.highlight background)
      

  12. Kajo
    Permalink to comment#

    I am really curious about classes like “left50″ or “bigGray”. What is bad about it? Is there any article to read and study? Because I am using it sometimes and I would like to know where is problem.

    Thanks a lot.!

    • Devin Dombrowski
      Permalink to comment#

      This is the one point I take issue with. A class of left50 is fine if that class only and will always “do that.”
      For example if left50 is just floating left and has width 50% then why title it anything else? If at some future point you want the element to be, for example, 40% width, then change its class to left40.

      960gs has class names representative of their styles.

      Just for clarification, I agree that most class names should be loose enough to accept style changes however clarity in the class name also creates a more readable markup.

      Ex: ul.list_normalize.left50

      If you knew the style sheet you could easily read this markup and know (for example) that this ul had no margin or padding and was floated left with 50% width.

      I favor readability over ambiguity.

      Just my thoughts, though I am open to critique.

    • Semantics is very much a personal thing, there’s no “right” answer really

    • @Devin – It’s not really correct to use left50 as a class because not only would you have to change the CSS file if the width moved to say 25px (so .left25) but would have to change the html/php file also – doubling up on work I feel.

  13. Forrest
    Permalink to comment#

    Honestly, you need a big disclaimer on this article. Based on what’s written, you have no business judging someone else’s CSS at all. Others have already touched on this subject – context is everything. You don’t account for:
    1. The developer integrating with code which they have no control over.
    2. Working with a CMS or other framework which auto generates classes and other code. It may not be logical, but the output is required.
    3. Other developers having modified the code since the dev worked on it. Maybe it looks the same and has the same end result, but no dev goes back through old sites to see if any of the code has been changed since they worked on it.
    4. JavaScript that modifies CSS. Not all of us get to choose how JS gets integrated, and if it bastardizes the CSS.

    There’s many other scenarios where a good CSS dev would fail all of your tests.

    • There is a section called “Why?” at the top of this article that goes over why you might need to do this. Those are all valid points, but I’m imagining you would either know about them already or it would come up in discussion.

    • Forrest
      Permalink to comment#

      Chris, yes, I read that. However, it doesn’t seem like a safe assumption that everyone will know they can’t just take your test at face value. Even after discussions with people, I’ve found many interviewers don’t know the code well enough themselves to understand such scenarios even with a discussion.

      I imagine this page is going to get ranked very high for SEO. Thus many interviewers are going to be reading this page and armed with the misguided info, passing bad judgement on good developers.

    • Permalink to comment#

      If that is why a good developer is passed up it’s probably doing them a favor that they don’t get that job.

      Having said that it would probably only take a sentence near the start to clear it up, perhaps that it is easier to judge developers on personal code as a lot of factors influence the standard of agency code *sigh*

      Great article none the less!

  14. The comment shout repetitiveness is basically incorrect when it comes to CSS. It’s the entire reason why things like LESS and SASS exist and they should be judged to that standard. But theres only so many tricks you can use to reduce repetitiveness in complex rules like box shadows and gradients when sticking toncss itself (until CSS variables and some other stuff become commonly supported). I would refine it by saying that the existence of AVOIDABLE repetition is the indicator of good/poor CSS.

  15. I actually inherited a very large project recently where everything is classes and have no control of some of the HTML output, but some styling needs to be page specific, so doing things like this…

    .article #comments ul > li > a.button {
    /* Crazy town */
    }

    is unfortunately necessary. If I had the time to re-write all of it, believe me I would. Absolutely the wrong way to use classes IMO. This is one of the huge downsides of compartmentalizing the development within agencies also.

  16. Here’s my CSS Tips. I’m not going into the justifying details, but if you use these tips you’ll be better for it.

    – Don’t use multi-word-class-names regardless of word_separator
    – Avoid IDs, except on the body tag and/or to identify elements for JS (not for style)
    – Identify content, not style. i.e. class names should never say anything explicit about something defined in the rules (no classes like “.one-third”)
    – Write down every class name you use during a project’s CSS development life cycle

    Also, Kudos to anyone above who mentioned context. Arguing against !important, for example, is ridiculous in the face of integrating with systems you don’t have total control over. And, at least for me, the smaller the project the more OK it is to break the rules. CSS practices apply to longevity and maintainability above all… super small projects that you just need to dump quick need not always apply. You can always refactor later if the project gets that large. If you’re that good at writing CSS in the first place, a refactor won’t necessarily be that hard.

    That being said… I also think there is some validity to purposefully not trying too hard. Sometimes you “discover” the commonality of your presentation trends by being a bit more sloppy as opposed to trying to overengineer right away. Writing great CSS is like writing great English, it requires many drafts and many iterations to be concise, to the point, but most of all, still interesting.

    • Amen ;) CSS is indeed written in a certain “style” (no pun intended here ) and even though some basic guidelines should be in place, there is a reason why certain “tools” are available such as “!important”.

      All that, spiced up with a sense of logic and cleaning up afterwards goes a long way!

  17. Antony
    Permalink to comment#

    I think a large css file isn’t always endemic of bad CSS, it can be an inconsistent designer.

    Great suggestions above. Also naming is important to me. Name things for what they are and not what they do:

    .left-column { float: left; }         /* Uninformative and not very flexible */
    .secondary-content  { float: left; }  /* Descriptive and flexible */
    
    
    .red { color: red; }    /* Must always be red */
    .error { color: red; }  /* Can be changed to any colour */
    
  18. S. Tanner
    Permalink to comment#

    As far as comments in the CSS, I never do. As I’m the only one working on it, I see no need for comments. Adding comments for me would be like covering my room in post it notes with door, wall, desk, bed, etc. written on them. If it’s to be posted as an example or written for someone else, comments make sense.

    As for my personal CSS files, I always like to go back and double check my work if I ever go over 7 kb for stand alone CSS. I also keep CSS files for styleswitcher purposes to 100 bytes or less.

    Also, once a month or so, I scrub my CSS. If I’ve ditched a class in my HTML files, it doesn’t make sense to keep it in the CSS file. Likewise, I also check for conflicting styles. If a parent specifies a border, the child specifies no border, and another child specifies another border, it’s time to look into why and find a way to streamline the code.

    • I comment my css even when I’m the only one working on it because if I have to go back to it in six months, there’s no way I’m going to remember what everything is or where I put everything.

    • Ryan
      Permalink to comment#

      You must be the guy who wrote the CSS for this project I got hired to clean up. Fortunately, I bill for the time of figuring out what the less-expensive-guy-who-built-the-site was trying to accomplish.

  19. Pierre
    Permalink to comment#

    These are all things I bitch about as well. However it is very hard to keep best practices in today’s CMS focused web development. Often you inherit class and id names, along with a TON of CSS from 3rd party developers. Some are pretty logical, some are just crazy.

    Sometimes you can just comment out the stylesheet and start from scratch. Sometimes you have to go digging through extensions and alter things to fit your needs.

    I wish I could just create a simple site with a CSS file under 100k.

  20. Red
    Permalink to comment#

    BEST talk I ever heard about “CSS best practices”.
    Called, “CSS for Grown Ups: Maturing Best Practices” by Andy Hume

    http://schedule.sxsw.com/2012/events/event_IAP9410

    Give it a listen it will rock your (css) world!

  21. The main points have been covered here. It would be interesting to know what anyone in this thread thinks of the following:

    Dividing up various areas into separate style-sheets and then minifying them into one upon the site going live – I am working on a site that is based on Skeleton and the css files are frikkin everywhere!

    Organizing the style-sheets into a specific order i.e. alphabetical

    Are these considered “best practices”?

    Thanks!

    • Jesus Bejarano
      Permalink to comment#

      Alphabetical order?. That is ridiculous you should organize them per priority instead.

  22. richarde
    Permalink to comment#

    I’ve recently started writing my CSS as LESS. For me writing CSS in this way means my selectors are leaner and overall the code is easier to read and much cleaner as a result..

  23. I’m missing one !important indicator for _not so good_ CSS which to me reveals immediately the level of css-knowledge of the coder: that is contradicting attributes. I ever so often stumble upon something like .left_img {float: left; clear: left;} or div {display: block; display: inline;} – that is really someone not knowing what to do and just trying.
    Another similar indicator: attributes overriding themselves like .error{color: red; color: pink;} – each time I see stuff like that I really get a sort of horror when I have to continue to work with this CSS. It means to never exactly know where attributes are set. Consequences is a lot of debugging and searching – time that could have been spent better.

  24. Kenny
    Permalink to comment#

    Good lord, i read every single comment and followed every link…potential brain meltdown pending…

    Anyhow, I love all of the input, however for my self i will say using !important as it be, is 99.999999% for me, just utter laziness, and as the argument seems to be, clients usually don’t care, they just want results and ASAP.

    I suppose if i was going to write it to be scrutinized I would make sure there were no instances. Either way, I do find myself sticking to a solid construct not for others but for myself…I have had to go in and change stuff from a year or two in the past and I learned early on not having some sort of system and clean code can really bite you in the ass.

    Excellent article, loving the controversy ;-P

  25. Not sure about the selector test. I know that it’s best practice to keep your selectors as short as possible, but I prefer correctness over briefness.

    Shortening your selector either means littering your html with extra classes (bleh) or making the selector less specific. This becomes a problem when the html components are extended with new and unforeseen elements or particles for new releases or updates of your site. Suddenly the old selector starts to apply to more elements than it was intended for, which is a clear and obvious recipe for disaster. This is sure to lead to ugly and unmaintainable code.

    So I’d rather check for correctness of selector with only as much overruling as possible, rather than short/brief selectors.

  26. One thing to look for is their treatment of IE – are they totally ignoring it?

    Are they using old school IE hacks? (like the underscore hack)

    Are they using inline conditional comments or doing the cute “add the IE class” to the html tag trick?

    The IE list goes on and on. Those are a few obvious ones.

    • hacks are worse for me as they are hard to find and easy to overlook
      html class is nice as you can put it in your stylesheet at one place

  27. Georgina
    Permalink to comment#

    This article is unbelievably timely for me. I’m currently employed as a junior front end dev. This is my first pure front end role, which means I’ve had to suck up being labelled a junior. Last month we hired a new senior front end. He went sick so I had to step in. His code contained all these errors and more. I’m now wading through his code trying to meet the same deadline in half the time he’s already had. I’m going to pass this article on to my pm…

  28. As others have touched on, when dealing with CMS platforms with tons of third-party modules, the class names and HTML output is often embedded deep down in the PHP, or in constantly variable, client-edited HTML, making it hard to refactor the structure to suit the CSS. While this advice is great for many other websites—and some of the advice certainly applicable CMS stylesheets—some of the redundancy and specificity is a necessary evil when it comes down to theming with ZEN stylesheets for Drupal, for instance.

  29. I’m surprised http://www.slideshare.net/stubbornella/object-oriented-css hasn’t been mentioned yet, though its been quoted quite a bit.

    In addition to the above, I’d also look for

    1. Elements in rules that are common and can be nested, e.g. styles like
    .mymodule div {}
    especially when combined with font-size, which of course will (as it should be) be in relative units.

    2. CSS causing accessibility failures

    For example, if an element has position: absolute, it needs checked in the browser to make sure it doesn’t sit over things when text gets scaled up. Setting height in pixels and overflow: hidden also need checked in-browser for cutting off content when text is scaled up. There are a lot of others around outlines, changing on :focus as well as :hover, display: none vs. position: absolute and left:-99999px, etc.

    And if you/others don’t buy into the corporate responsibility aspect, then think of it this way: the code is exposing your company and/or your clients to litigation.

    3) Backgrounds that won’t expand if the text gets longer

    4) Not taking advantage of the cascade is always a good one.

    5) Alternatively, reusing a style where the name of the style would lead you to believe it only applied to a particular area. Changed some padding in a style used by module A then found module B fell apart? That one.

  30. @ Matthew J. Sahagian – Why not use multi-word class names? Are you on a camel-case crusade or do you have a good performance reason?

    I use camel-case for scripting variables and under-score names for CSS. Besides mixing two different programming paradigms, it makes my code more readable.

    re: the ‘!important’ issue… while I agree in general, there are times when it’s a good idea, such as when using @media queries for screen size or printing, to make sure code is over-written regardless of whatever else is going on or what may change in the future.

  31. Zachary
    Permalink to comment#

    How many people minified their CSS? On a small static 7 -12 page site would it be worth it?

    • minify in order to get faster load time as the file size is smaller

      if you work on big project, minify !
      in case it is web where you want to let people look at your code, do not minify as you want it human readable

  32. Melanie Archer
    Permalink to comment#

    I suggest running rubbish CSS through tools like CSSLint, CleanCSS, Chrome Inspector CSS Selector Profile, or Dust-Me Selectors to generate reports to show how flawed the style rules are. Site owners are less likely to dismiss the findings as opinion.

  33. Permalink to comment#

    Great article. It’s always good to learn ways to improve. It sure takes a while though to get your own system down that works for you. Sloppy code may not necessarily be because of a lazy designer/developer but someone that just hasn’t found their fit yet.

    Great read though, I struggle with using templates as a starting point, it’s hard to hop into someone else’s groovespace. I am thinking about making some of my own default templates especially with all the responsiveness going on.

  34. Michael
    Permalink to comment#

    Good article, just wish more developers would follow “good coding practice”.

    WordPress themes are a prime example, every theme I’ve been interested in have some very “dirty” HTML and CSS code.

  35. Good article, I think another test (and this might be in the comments, I only read the first dozen or or) is what the end of the CSS file looks like.

    With sites that have been live for awhile or sites that have gone through rounds of client feedback, it’s interesting to look at the bottom, and see if a range of fixes have been tacked onto the end of the file. Which if on a large project or a long term client can just become fix on top of fix.

  36. Dax
    Permalink to comment#

    Here’s my advice:

    Get a life! Let chaos rule! Cheap dirty CSS for life!

  37. Knut
    Permalink to comment#

    Sure sign for me is the use of @import in production CSS.

  38. Even though I understand certain “standards” or “code of conduct” must be applied (for ones own sanity in the first place) when creating CSS. Yet I must add that in the end, as long as everything looks nice, works nice, works fast, all is good. If u have to, indeed, work together in a team on one file, then some rules are most likely very much appreciated :D

  39. for those of you saying to never ever use the !important declaration, clearly you have never tried to work with modifying some dojo themes. At least in < dojo 1.5 their CSS is laced with unnecessarly long selector chains with lots and lots of !important thrown in. (Seriously, the dojo staff have no idea how to write CSS)

    And unfortunately, for the stuff I work on I can't remove the base dojo themes, because that would require too much time to move over the styles we do use, and make sure the entire application still works.

  40. Of course, this is all pretty subjective. There are many different organizational styles. Some people like to alphabetize all the properties in a selector. Personally, I like to group positional things first (position, display, margins/padding, float, etc), followed by borders, colors, and other special effects, and finish up with text styes.

    This mirrors how at a higher level, I similarly start out with general rules that affect overall layout of the page, then work down through progressively more specific elements (which is natural, given the way the CSS cascade works).

    As far as the “bad” selector example goes, that didn’t look too bad to me. I can easily imagine use-cases where that would be a perfectly fine selector. When you start seeing multiple ID selectors in a rule (e.g. ‘#main #content #comments .foo’), I start to wonder, though. In a CMS-driven site, it can sometimes be necessary, but hopefully not. I generally only see that sort of thing in CSS that has been inherited from some other developer, and/or in cases where a site has been through multiple design overhauls without the opportunity to dump old code and start from scratch. Which is unfortunately common in real-world projects.

  41. I ALWAYS respect a front-end dev that will admit that his/her CSS is perfect. Let’s face it, we’ve probably all gone back and looked at our old CSS and realized things should have been done differently. I know I have. What’s as important as anything is a CSS coder who constantly tries to improve technique. A good guage of this: when’s the last time they re-built their portfolio site? I’ve been working on a new dev/design for mine for a few months based on things I’ve learned over the last 6 months.

    For more technical stuff, do they use interesting pseudo-selectors like:

    
    :before {/* stuff */}
    :after {/* stuff */}
    :first-child {/* stuff */}
    :first-of-type {/* stuff */}
    

    etc, etc.

    Do they use global selectors like:

    
    section[id^="blah"] { /* stuff */}
    section[class*="foo"] {/* stuff */}
    

    To me, those things show a greater grasp on actually ‘thinking’ about structure/specificity/future modification/dev and simplifying many of the CSS rules that may not be needed.

    A dev that admits they don’t write perfect CSS (especially when they actually DO write exceptional CSS) is rare.

    • Whoops … in the first line I meant to say I respect a front-end dev that can admit his/her CSS IS NOT perfect.

    • hehe, I figured something like that when i read the comment (see even comments are vulnerable to some tiny mistake that could change the meaning 180 degrees :p) AND you have got a point when it comes down to “grasping css” while using more advanced selectors. unfortunately only available for more advanced browsers too, so, this css should only be used when applying progressive enhancement methods. (or a jQuery based mimicking css3 .js file). Either way, This article here surely touches some sensitive strings. (and I too am the first to admit my css is not and will never be as perfect as I want it to be… I see CSS a bit as an ever evolving way of doing things, it is a living creature that will evolve in time and will have many different approaches to the same problems. While a base knowledge of it all might set a standard, in the end it is the coder’s “hand” or “signature” that eventually portrays the true mastering of it all. And as there are many different painting styles out there, there will also be many different ways of coding out there. This said, it’ll probably not be the last word on the subject matter at hand.

    • @CiNiTriQs – Spot on!

  42. Permalink to comment#

    Very useful list to judge CSS. It’s always good to learn something new. Every developer has a different style of coding and this test can be helpful to judge CSS of any developer. I think code should clean and easy to read.
    Thanks for this wonderful post :)

  43. For tiny single-developer projects where the person creating the CSS is also compressing it and FTPing the files to the “production” server you might want to judge it like this, but then the overhead of aiming for best practices is probably wasted on projects like that, and then the judging can stop at the obvious test. CSS code just doesn’t pack the tricky business logic that makes it worth the investment to make it as maintainable as a core system. Good developers have enough experience to know when to break the rules, and some schmuck using a post on css-tricks.com to judge them will only complain about not being able to find good developers because the ones that write code by these rules aren’t the ones that can solve problems. The problems that they have to work in a team, with a different coding style then they are used to, with legacy code, for embedded browsers worse than IE, with untouchable HTML, CSS for SVG, with a tight budget and strict deadlines, etc. Code is about the last thing I look at when hiring someone.

    But the lack of a namespace in classnames is a tell…

  44. Permalink to comment#

    I’m a self taught front end developer and I often wonder if my CSS is “good” this definitely helps me gauge where I’m at. For the most part I pass! I think my biggest flaw has to be commenting and I don’t use shorthand’s too often. This was a very nice read, thanks!

  45. rtpHarry
    Permalink to comment#

    I was expecting to read a section in the article that mentioned browser hacks?

  46. Idiomatic CSS is very good; I helped translate it into french (so know it pretty well) and believe that it is a good starting point.
    You don’t have to do what is says exactly; it just gives you an ides of how to make things work consistently and provides a ‘best’ example.

  47. Another vote here for Idiomatic CSS. It’s a nice condensed reference with solid principles.

  48. Simon
    Permalink to comment#

    Is there a way to use CSS to hide all the !important tags afterwards i.e. from the bastards who want to ruin your livelihood by revealing your incompetence?

    As a punishment for using it, people should write out a thousand times:
    .lazy-developer { use-!important-as-a-get-out-of-CSS-jail-free-card: none !important;}

    • Permalink to comment#

      Not really, I myself hate using !important, but the structure of multiple CSSs and the haphazard way that they can be called in certain (not to be named) CMSs can mean that it’s needed.

      I also tend to use important a little in overriding for responsiveness, don’t judge me!

      In basically all circumstances, important! is only used by me when I’m really being pushed for time, and have no choice =)

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".