Try Tuts+ Premium, Get Cash Back!
Should You Start Using CSSLint?

Should You Start Using CSSLint?

Getting our code reviewed by a pro is a great way of improving code quality but what happens if you don’t have access to a rockstar programmer? You do the next best thing and grab a ‘lint’ for that language.

Today, I’d like to talk a little about CSSLint, a recently released code analysis tool for, you guessed it, CSS. Join me after the jump!


What Exactly is a Lint?

Let’s hit Wikipedia for a definition:

Lint is a tool that flags suspicious usage in software written in any computer language.

Basically, a lint looks at our code and checks for bad programming practices. Undefined variables, inefficient constructs, things like that.

You’re probably wondering why you’d ever need such a tool. Let’s face it: not all of us possess supreme knowledge of what we’re working with or have the luxury of getting our code peer reviewed. In these cases, sticking our code in a lint is the next best option. And unlike clean up tools, lint spits out tidbits about your code and how to improve it.


Introducing CSSLint

CSSLint

Created by Nicholas Zakas and Nicole Sullivan, CSSLint is an open source tool that checks your syntax against a set of predefined rules to root out possible inefficiencies and make sure that your presentation works as expected with little surprises.

After heading over to the CSSLint site, you can merely paste in your source CSS and choose which rules you’d like enforced. Hit the lint button and CSSLint will start eroding your smugness.

CSSLint

If you’re a Node junkie like me, there’s a version for that as well. Just type in sudo npm install -g csslint and you’re good to go!


The CSS Lint Rules

Let’s take a quick look at the rules that CSSLint enforces.

  • Parsing errors should be fixed
  • Don’t use adjoining classes
  • Remove empty rules
  • Use correct properties for a display
  • Don’t use too many floats
  • Don’t use too many web fonts
  • Don’t use too may font-size declarations
  • Don’t use IDs in selectors
  • Don’t qualify headings
  • Heading styles should only be defined once
  • Zero values don’t need units
  • Vendor prefixed properties should also have the standard
  • CSS gradients require all browser prefixes
  • Avoid selectors that look like regular expressions
  • Beware of broken box models
  • Don’t use @import
  • Don’t use !important
  • Include all compatible vendor prefixes
  • Avoid duplicate properties

If you’re anything like me, a few of the rules must have had you flummoxed.


Do the Rules make Sense?

Quite frankly, yes, no and everything in between.

After lurking at a number of discussion boards and IRC rooms, I found out that many developers seem to be in uproar over the rules and maybe right so. Let me attempt to explain why most of the rules make sense but others do not.

The Controversial Rules

Don’t use IDs in selectors

IDs shouldn’t be used in selectors because these rules are too tightly coupled with the HTML and have no possibility of reuse. It’s much preferred to use classes in selectors and then apply a class to an element in the page.

This one struck a nerve with a lot of developers since we’re quite accustomed to assigning IDs for the main structural components of a layout like the header and footer.

CSSLint argues that the styling for such elements, by definition, can’t be directly reused. If you want dual sidebars on your page, a class lets you reuse styling while an ID will not.

Keep in mind that just because a class can be reused doesn’t mean it has to be. Unique classes are perfectly acceptable and a swell way to reuse styling if the need arises.

Don’t qualify headings

Heading elements (h1-h6) should be defined as top-level styles and not scoped to particular areas of the page.

Most developers, including me, have gotten used to writing context sensitive headers. As in, we define separate styling for headers depending on, say, which page it is being displayed on. An argument in favor of this approach is that it moves all cruft from the markup to the stylesheet. You can merely define a tag and let the CSS cascade accordingly.

CSSLint argues that such an approach compromises the predictability of your design. If someone else were to pick up your design and tried putting in a heading somewhere, he/she would need to be aware of the context and placement of the element. With headings defined unconditionally, he or she can use a heading anywhere confident of its presentation regardless of its parents.

Heading styles should only be defined once

Heading elements (h1-h6) should have exactly one rule on a site.

An extension of the rule above to improve predictability of presentation. Right or wrong, keep in mind that this basically excludes including some sort of reset code within your stylesheet. Every reset sheet works on your headings as well and thus CSSLint will mark it as an error.

The Questionable Rules

Don’t use adjoining classes

Adjoining classes look like .foo.bar. While technically allowed in CSS, these aren’t handled properly by Internet Explorer 6 and earlier.

With this rule enabled, CSSLint flags rules like .nav.red, with the official reason being that Internet Explorer 6 and below don’t play well with the selector. I respect the developers but I have to disagree here. Just because it doesn’t work with Internet ‘Dev-buster’ Explorer 6 is not a great reason to stop working with a useful feature.

Beware of broken box models

Borders and padding add space outside of an element’s content. Setting width or height along with borders and padding is usually a mistake because you won’t get the visual result you’re looking for. CSS Lint warns when a rule uses width or height in addition to padding and/or border.

The box model maybe broken but almost every front end developer I know is intimately aware of the shortcomings and how to overcome the disparities with implementation. Are we really ready to give up a layer of control because some older browsers have a different implementation?

Don’t use too many web fonts

Using web fonts comes with performance implications as font files can be quite large and some browsers block rendering while downloading them. For this reason, CSS Lint will warn you when there are more than five web fonts in a style sheet.

I don’t foresee a situation where I’d be using more than five fonts in a page but I feel that dipping into this territory is a bit questionable. If anything, this is a design flaw than a development flaw. If a developer is referencing five separate fonts in his stylesheet, chances are, it ain’t by accident.

Don’t use too many floats i.e. abstract the functionality away

CSS Lint simply checks to see if you’ve used float more than 10 times, and if so, displays a warning. Using this many floats usually means you need some sort of abstraction to achieve the layout.

While I concur with the creators’ argument that having more than ten instances of float is a bad idea, I also feel that this will affect the markup once past a given size.

For example, in a situation where you’d want to float two elements, traditionally you’d use:

<div class="container-1"></div>
<div class="container-2"></div>

… and the styling, by traditional methods.

.container-1 { width: 70%; float: left; }
.container-2 { width: 30%; float: left; }

The CSSLint method would be abstracting the float like so:

<div class="container-1 float"></div>
<div class="container-2 float"></div>

… and styling like so:

.container-1 { width: 70%; }
.container-2 { width: 30%; }
.float { float: left;}

While I agree that this is a viable approach, I feel that the markup will get significantly crowded once you try to abstract more away. I’d rather see a class containing most of its styling in one place than clutter the markup with 10+ classes. Again, I feel that this is a subjective topic.

The Obvious Rules

  • Remove empty rules
  • Avoid duplicate properties
  • Zero values don’t need units
  • Vendor prefixed properties should also have the standard
  • Parsing errors should be fixed
  • Include all compatible vendor prefixes
  • … rest of the rules

All of the rules above adhere to the current standard practices. Sure, some of the rules have little real world significance, like zero values not needing units, or will be caught by a decent IDE, like parsing errors, but nevertheless these are good rules to have in a CSS test suite.


A Few Concerns

CSSLint is going to help a lot of developers down the road but…

CSSLint is, no doubt, written by developers with great credentials and is definitely going to help a lot of developers and designers down the road.

What I find a little irksome is that a lot of the controversial rules come from Object Oriented CSS, a CSS framework intended to let developers write maintainable CSS. While I have nothing against the framework, and its paradigm, you’d have to agree that it’s a way of doing things, not the way to do things.

As opposed to JSLint where I feel like all the rules make sense, with CSSLint, it feels like I’m being told that one style of writing CSS is right and the others are wrong. It’d be like someone asking me to give up the Beatles because Rolling Stones is their preferred band.


It’s Only a Tool

Tools are just that — tools.

Of course, we, as a group, tend to be rather clingy when it comes to our code. We don’t enjoy hearing that our code could have *gasp* potential issues or be written in an entirely different way.

The main thing to make a note of here is that CSSLint is, ultimately, a tool. It merely lets you know that some of the areas may have errors.

CSSLint doesn’t have to be the iron fist around which you base your entire ego on. There’s no reason to bend over backwards to avoid a warning if you know precisely what you’re doing.


So, Should you Start Using CSSLint?

Yes.

In CSS, as in integral calculus, there are many solutions to a given problem. There necessarily isn’t a ‘best’ way to do things — you may favor readability while I may favor efficiency. What’s important is that you realize that each and everyone of us have our unique way of doing things.

If you don’t have the same perspectives towards solving a problem, you may disagree with another approach and may even find it questionable.

Having said that, there’s never a good reason for not learning new things. Looking at problems from the perspective of another developer is a great way to see if you can learn something new.


Wrapping Up

What do you think about CSSLint? Find it useful? Confusing? Has it helped with your real world problems? Let us know in the comments.

Be excellent to each other and thank you so much for reading!

Siddharth is Siddharth on Codecanyon
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://css3.bradshawenterprises.com Rich

    The “Don’t use IDs in selectors” rule is absolutely ridiculous. There are many many cases where the element you want to select is by definition unique (i.e. a logo in a header, a sidebar, the main wrapper etc). IDs are quicker to select than anything else, plus you are able to get the benefit of the speed increase when using JS as well.

    Understanding when to use IDs and when to use classes is an important part of learning CSS, and giving advice to newer developers to ignore IDs is madness!

    • http://oddnetwork.org haliphax

      I wholeheartedly agree. Nearly everything in the CSS standard has its place–and like many different portions of the HTML standard, if you don’t know why they should be used for particular scenarios, it can get ugly (and quick). However, that’s not to say that it should NEVER be used.

    • Paul

      The chronology:

      I read the title of this article.

      I googled csslint.

      I visited the site and pasted in a css file I’d written recently on a site I’m working on.

      The first ‘warning’ I get back: “Don’t use ID selectors”

      I sit there for a second. I think about it. Am I doing something wrong? No – no I’m not. This is stupid, and I don’t respect the result (also I couldn’t seem to click on the result to get an explanation).

      I come back here and read the comments in the article – pretty happy the author pointed out that csslint is not necessarily 100% to be relied upon.

      Decided to write an angry comment on it.

      Saw your comment.

      Decided to do this.

      There you go.

      • http://www.philoveracity.com Verious Smith III

        @paul – I think I went through just about the same process. I concur; the no ID’s in selectors is a rule i am not in favor of.

    • Magnus

      They are talking about using ID’s in CSS. Not JS.

      You can still have <div id="header" class="header" and then use .header for styling and #header for the JS.

      I do think this is ridiculous, as well thou. If I have a class namned "header", then I can't really stick that class on anything else. And calling it something else won't make as much sence either.

      And I'm really against adding a lot of classes on an element like: <div class="mybox float somethingelse"
      If you just put the class "mybox" on the div, then you can change the apparence on "mybox" without having to look through the entire code for all instances of "mybox" and remove or add the new classes.

    • http://www.ibrightdev.com Justin St. Germain

      i couldn’t have said it better myself. I use ID’s for all the main parts of the layout, what I like to call the “skeleton”. I use classes when i may, or may not, reuse the same style on another element on the same page. like this…

      <div id=”wrapper”>
      <div class=”container”>
      content here
      </div>
      </div>

    • Matt Ritter

      “Understanding when to use IDs and when to use classes is an important part of learning CSS, and giving advice to newer developers to ignore IDs is madness!”

      Well put.

      This tool is there to make you a better front-end developer. It should help you take a step back, re-organize, and work a little more clearly through your layout. I wasn’t a big fan of this tool on first use, but once I starting using it more and more often (ignoring a few of the annoying “errors” that I think are nonsense), it really has made me much more efficient in writing my selectors…and I’ve been coding for years!

      As far as not using IDs in selectors–I think that’s bogus. I use them all the time. If you have no plan to use two “headers” in a layout on one page (if you do then it’s not really a header), then what’s the problem?

    • http://www.BlaineSch.com BlaineSch

      I agree, you NEED to use ID selectors. If we broke up our entire “#footer” or “#container” class into multiple we’d probably end up with our code having EVERY CSS attribute in a class. Each class only containing a single attribute.

      That is stupid. Imagine a live site, your footer would contain like 10+ classes.

    • http://williamhutter.com william

      @Rich

      I like to use classes only for styling and IDs just for Javascript. At least, I don’t get confuse when I maintain the site. It’s just easier to read.

  • http://oddnetwork.org haliphax

    Also… if you need a “rockstar programmer”, here’s an idea: Hire/outsource one. Sheesh. :P

  • Daniel

    This would also be an excellent tool for already existing sites.

    I will be sure to use this.

    Great article by the way.

  • Chris

    I can’t see how this tool would be very useful to anyone. When it reports things like “Don’t use IDs in selectors” to a beginner (unfortunately, that’s actually the entire error text), it will just lead to confusion.

    I’m sure the creators had good intentions, but CSS is not rigid enough to evaluate with a lint tool. I think most people who think they could benefit from this tool would be better off picking up CSS Mastery (or another highly-rated CSS book on Amazon) to learn the basics from a master. If you want to be good, you can’t rely on a free web app to highlight your mistakes. You need to know what’s good practice and what’s not.

  • Jose Gomez

    Nice Tool, is there someone for PHP?

  • Roland

    IMO this tool is misnamed.

    I’m glad they added the ability to deactivate those rules which seem controversial, but it should be named OOCSS-Lint – that’s the *opinions* they are pushing/supporting. At least with the source on GitHub, someone could fork it and make a CSSLint that was less opinionated, or even one that was targeted for beginners, etc.

    • Jason

      I completely agree.

      The author hits it on the head as well.

      “Lint is a tool that flags suspicious usage in software written in any computer language.”

      CSSLint doesn’t do the above. It compares your code to the OOCSS spec. Unfortunately some of the OOCSS spec is in itself ‘suspicious’.

      It would be a far better tool if it made the OOCSS element of it something you had to manually choose to validate against. It should be noted when I last looked a few weeks ago both the CSSLint + Nicole Sullivan’s site fail miserably when put into CSSLint.. what does that say about the usefulness of the tool?

  • http://www.graphicrating.com Andy Gongea

    I think you are missing the point here.
    CSSLint outlines some of the issues in your CSS but doesn’t impose a certain way of writting CSS. I use it in big projects to eliminate !important and to see what are some of the issues in my code – vendor prefix or overusing floats and unsupported CSS3 stuff.

    Cheers!

    • http://www.ssiddharth.com Siddharth
      Author

      I could be wrong but beginners take to tools like these quite quickly after which reasoning becomes quite circular.

      It’s right because it’s mentioned in the tool and it’s in the tool because it’s right. I have nothing against the tool or its authors but I wish they were a little more transparent about the rules themselves. Potential devs will be able to parse some of the rules, say the ID issue, if they’ve been exposed to OOCSS before.

      • Paul

        Excellent comment Siddarth. It’s good to see you’re taking a healthy critical approach to this.

  • Chad Hietala

    This is a pretty trough overview of CSSLint, however I would have mentioned that this “rules” are largely based off of the OOCSS framework by Nicole Sullivan. Looking at that framework and then looking at Lint you see a 1 to 1 comparison.

    On a whole I agree with all the rules that CSSLint puts in place and here’s why. Creating reusable and extensible modules cuts down on CSS. The only good way to achieve this is to use classes to define and extend components of a site by attaching a new class when something needs to change.

    As for headings one thing I suggest is creating subsequent classes for headings like h1 .h1, h2 .h2, h3 .h3 etc. This way the tags can still follow the page hierarchy but you can just slap a class on the element to change it’s presentation IE <h1 class=”h3″ %gt;.

    Floats should be held to a minimum largely because they cause the page to reflow slowing rendering.

    Once again OOCSS principles are based on large scale implementations of CSS. I suggest looking at OOCSS http://oocss.org/, DOM, HTML5 and CSS3 performance by Paul Irish http://paulirish.com/2011/dom-html5-css3-performance/ and this presentaation by Nicole Sullivan http://www.stubbornella.org/content/2011/04/28/our-best-practices-are-killing-us/

    • http://www.ssiddharth.com Siddharth
      Author

      I do make a note that the rules come from OOCSS.

      I’m not arguing that these rules are bad, per se. I just think that this is one approach to minimizing CSS bloat, not the only way.

  • http://dougneiner.com Doug Neiner

    I felt this was a fantastic — and accurate — review of the CSS Lint tool.

    Too many of the rules are just too subjective to be a pleasant default. I may use it from time to time to find syntax errors or certain things, but I really doubt it. Too much about CSS depends on the situation, browser goals, etc.

    One interesting point that a friend pointed out to me on twitter (And it wasn’t original to him either) was if you check the CSS Lint website’s own CSS file through the tool, it produces 69 warnings. If the creators of the service didn’t find the rules strong enough to code against for the site, why should I?

    • http://www.amazon.com Hemant

      Gud catch Like it

    • http://www.awkm.org AWKM

      Before reading your comment I did exactly that and smiled when I saw the 69 warnings.

      I was worrying when I plugged the CSS for my blog in and got 84 warnings. I guess people can get worked up about a tool that is simply offering some good advice (and some not so perfect as we can see from the comments here)

      I still think it’s worthwhile to go through and fix any of the recommendations you agree with. I’m about to.

  • Alistair

    .hello:kitteh {
    sound: ‘prrr’;
    }

    Surely not valid?

  • Doug

    From the same person who brought you ‘object orientated CSS’. HA. Enough said

  • http://themeforest.net/user/wizylabs/portfolio?ref=wizylabs Taha Hesham

    Nice tool! but I dont think ill ever use it. Some of its rules I already implement in my CSS code but most of the others are a matter of personal preference and mine are against its rules most of the time.

  • kankuro

    All of us has a rule in life…. for web developers… if you think that this tool is not useful to your arsenal then don’t use it… if it is, then use it… thats very simple :D

  • kankuro

    I just used this tool for the CSS file i made in one of my project… i found it very helpful. It just indeed show my miss coding of the CSS… nicholas and nicole… thanks a lot for creating this tool…

  • kankuro

    I just used this tool for the CSS file i made in one of my project… i found it very helpful. It just indeed show my miss coding of the CSS… nicholas and nicole… thanks a lot for creating this tool… and also to you Siddhart for posting it…

  • w1sh

    C’mon, we already have a lot to pay attention to. You expect me to start checking my CSS for errors now? Pfffft! Like I’ve got time for that!

    *continues browsing reddit*

    • http://www.ssiddharth.com Siddharth
      Author

      ಠ_ಠ

  • http://www.футболмастер.рф alex

    Thanks. Very interesting tips.

  • http://www.xcellence-it.com/ Xcellence-IT – India

    I would like to use it and see how it improves our code quality as far as CSS matters…

  • http://www.amazon.com Hemant

    great tute for great tool csslint, one confusion for “Don’t use IDs in selectors”
    as I heard id selector are always faster then class selector,

    so is it reasonable to use unique class selector in place of ID selector.

    any budy please answer to me .

    Thanks in advance,
    Hemant

    • Magnus

      The answer to your question is No.

      Using unique class selectors goes against the logic. ID’s are for unique selectors and classes are for resusible styles.

      The resasoning for the statement of ID’s being faster is that if your usig ID, the browser will stop looking through the elements on the page when it finds the ID, while the browser need to check all the elements if you’re using class.

      Although, i’m not really sure how big of a difference this acctually makes for the CSS in the real world (I mean, c’mon… are we talking about 0.0001 sec difference or something for rendering the CSS?). There is a noticable difference when you start using JQuery on the elements, thou. Especially on IE8 and lower.

      • http://www.amazon.com Hemant

        Hello Magnus,

        thanks a lot for giving solution to my question. felling supper happy with your answer.

        Thanks,
        Hemant

  • http://markasread.net evaisse

    Sad there is no Syntax checking on CSSLint, this must be one of the major point in what I like in JSLint. This kind of control don’t let developper do anything with case, space & indent. Pretty usefull when you work on a project with many developpers.

  • ironrunes

    the float rule got on my nerves, but then thinking about it, I’d just do something like this:
    .container-1{width: 70%;}
    .container-2{width: 30%;}
    .container-1, .container-2 {float: left}

    that would keep the markup readable, as long as containers are abstracted enough. :)

  • Mehdi Raza

    The only “problems” it gave with my code:
    >>> Don’t use IDs in selectors! <<<

    I hate it….

  • http://maxumi.com/ Michael Gunner

    The tool bitches about me using adjoining classes, and it’s sole justification is IE6 can’t handle them properly.

    Well, I’d love to see what they think about using HTML5 then.

  • http://www.group5advertising.com Dru Martin

    I’d be interested to see how CSSlint compares to the Web/Dev Toolbar’s ability to ‘validate CSS’. Anyone have any real world experience with this? I’ve used the Web/Dev Toolbar in the past and have found it to be frustrating in similar ways.

  • Gerben

    I think it’s a nice tool. If people are bothered with the more controversial rules, they could just untick the checkbox before checking their CSS.

    Besides the warnings you’re not concerned with it could give some other warnings or perhaps errors which do matter.

  • Mark

    The thing that I don’t really like about tools like this is that experienced coders don’t really need to told that their preferred way of doing something is wrong (because they will know about its pros and cons and they have made a decision to do it that way according to their situation or preference) and learners may well feel that they should take the advice as gospel and do it that way because it seems like it’s [a] correct and [b] a big issue, even though it might not be. I don’t think that it’s particularly constructive to get quite as prescriptive as that about CSS.

  • http://russelluresti.com RussellUresti

    ID Selectors:

    Using only classes ignores one of CSS’s most important features, specificity. These selectors are given different weights for a reason, and they’re meant to be used. Overriding specific styles

    Qualified Headings /Defined More Than Once:

    This ignores the fact that there’s a new heading outline order with HTML5 sectioning elements. You can re-use headings (h1 – h6) inside of sections, where before, you would not want to do this (the “only 1 h1″ rule). Headings, now more than ever, should be qualified (and defined multiple times depending on their section).

    My General Thoughts:

    When this tool first launched, there were things they just got wrong. The adjoining classes error was raised for IE6 and IE7, even though IE7 supports them (the tool said it didn’t). Now, I have no doubt that the people who created this tool are capable developers, but, well, yeah.

    The creators of this are proponents of OOCSS, which is great for large applications, but horrible for actual websites (or brochure sites, if you prefer the term). That explains a lot of the rules around ID selectors and what-not. The tool actually pushes a style of coding, which isn’t always the right way to do things.

    On the plus side, most of the controversial ones are warnings instead of errors, and you can turn them off if you don’t agree with them or they don’t make sense for your project.

    Ultimately, I won’t be using this tool.

  • Mike Hopley

    As usual, many people haven’t bothered to do their homework before pitching in with smug comments; ignorance begets confidence. You really need to watch one of Nicole’s OOCSS presentations — and watch it thoughtfully, with an open mind — before reciting the same old tired dogma. You can also read the OOCSS FAQ here:

    https://github.com/stubbornella/oocss/wiki/faq

    CSS Lint is not “stupid” or “useless”. If you think that, it’s because you don’t understand it.

    A better name might be “OOCSS Lint”. CSS Lint checks your code against OOCSS recommendations. If you hate OOCSS, then there’s little point using CSS Lint.

    Nicole and Nicolas have called it “CSS Lint” because they believe OOCSS *does* represent the best (current) approach for building good CSS. I happen to agree with them; but you’re welcome to disagree.

    But why not disagree in a reasoned and respectful fashion? Whatever you think of OOCSS, these developers deserve your respect (have *you* ever consulted for Facebook? Have *you* ever published a popular book on javascript?).

  • http://www.giulianoliker.com Giuliano Liker

    I tried it, it hurt my feelings, and I dumped it ;) Basically, I tested stylesheet from one of my latest projects and I got bunch of errors you mentioned above. After reading through all errors I realized they are not errors at all, just a different way of using CSS.

    It’s a good tool for beginners though.

  • http://webdesignertribe.com Ron James

    nice tip and its help me because i am a beginner. Thanks for this

  • http://nataliav.me Natalia Ventre

    I think CSSLint is a useful tool, as Siddharth said there are some questionable rules, so I uncheck that boxes and check for the errors and warnings that I want to avoid.

    I understand the idea behind the “don’t use too many…” rules, but using LESS there are going to be issues on the .css file, although the .less file uses abstraction via the mixins.

  • Jennifer

    I think CSSLint is a useful tool. The concept of not using IDs threw me off though. I’m glad about this article. I was wondering what opinions other people had.

  • Mike Hopley

    The issue about not using IDs keeps coming up, so I’ll try to explain the OOCSS rationale:

    One reason to prefer classes is that you can reuse the styles. But this is not the only reason.

    The other reason is due to specificity. Complex specificity is an obstacle to building scalable, maintainable CSS: because rules unpredictably override other rules, styles that should be unrelated can interfere with each other. You then end up “fighting” with your colleagues — or with “past you” — by piling more and more specificity into your latest styles, so that they will have high enough specificity to work. Nicole calls this a “specificity war”.

    One solution is sandboxing, where you specify that styles should only be applied within a certain container. For example: “#sidebar h2″ defines a heading style that has no influence outside the sidebar container.

    The problem with sandboxing is that it scales badly and it makes styles unpredictable. As time goes on or a site gets more complex, you add more and more sandboxing exceptions. This creates code that can be difficult to maintain or extend. It can also make your styles unpredictable: things arbitrarily change appearance depending on where you put them.

    OOCSS deals differently with the problem of out-of-control specificity. OOCSS wants you to keep specificity “flat”, so that there is no need for sandboxing. By taking specificity out of the picture, you also get a usable cascade (remember that first “C” in CSS?). You can use the cascade to define variations/overrides.

    In the way we’ve normally been writing CSS, the cascade is crippled: specificity overwhelms it.

    Sandboxing isn’t *always* a problem, however. Even if you’re an OOCSS devotee, you *may* prefer to use IDs in certain situations. Here’s what Nicole says:

    “There may be cases where you want to style using an ID, like header menus that are very specific, in this case you can use an ID to sandbox the particular element and be sure that the code written for it doesn’t impact the rest of the site. Think carefully before you choose an ID over a class, it is really hard to predict what people will do with HTML built from your CSS as the site evolves. If you have a choice, leave things as flexible as possible.”

    • http://11heavens.com Caroline

      Thank you, Mike, for your clarification about the ‘specificity war’ and the dangers of sand-boxing. This is much appreciated.

  • http://eriwen.com Eric Wendelin

    You can change which rules are applied, guys. I’ll admit that it’s not obvious from the documentation, but it’s there.

  • Dave

    One thing for sure – get CSS people in a room, and you’ll get big arguments. Not necessarily because they don’t get along, although we do get our share of strict grammarians, but mostly because it’s so flexible.

    Mike Hopley made the case for it better than almost anyone here. I can relate to taking the sandbox thing to an extreme, as some designers I work with are type-crazy, as in fonts, colors, and spacing of text.

    I have one advantage in that I’m rarely working on someone else’s code, and though I try to make my code very understandable, I’m usually the only one working on the CSS.

    I read the thing about heading styles being declared just once, and smiled. I always try to do this, and always have to make more. :) To further muddy the waters, an SEO person would use headers in particular ways, so he/she might not like the sizes used, and we have the designer vs. the client vs. the SEO. :-)

    And I thought I was doing well by using good resets! It’s very complicated.

  • http://www.bauglir.com Bronislav Klučka

    This is so bad tool event writing about it a bad idea due to advertising it…

  • Vasili

    Test 100 grid and css frameworks before you begin a new project, check out this cool things like less css and modernizr, check your site in 8 different browsers and 20 screen resolutions, make it mobile friendly – check it in 10 different devices, validate your code, do not forget about the file sizes that you include in your projects and finally test your styles in css lint. COMMON PEOPLE!

  • http://www.smouldendesign.com Shelby

    In your float example, you forgot one method to lower the amount of floats while also not adding any more classes:

    <div class=”container-1″></div>
    <div class=”container-2″></div>

    .container-1, .container-2{ float: left; }
    .container-1 { width: 70%; }
    .container-2 { width: 30%; }

    • http://www.ssiddharth.com Siddharth
      Author

      Sure but it just moves the problem to another domain. Now you have different sets of rules for the same class. And imagine what happens when the attribute set gets bigger.

      As I said, there are a number of ways to solve these problems and there is no ‘right’ way.

  • http://atinder.com atinder

    didnt mentioned why we should not use @import and !important

    While important is very useful….

    • Mike Hopley

      @import is bad in a *production* file, because it creates extra HTTP requests. It’s fine for organising your CSS into multiple files during development, but these files should be concatenated for production.

      !important is bad because it makes rules too strong. !important is a “heavy weapon” in the specificity wars I mentioned earlier. It accelerates the arms race. ;-)

      Apparently, !important can be useful on “leaf nodes” as a “mixin” for stuff like generic error formatting (say, turning text red). But in general, using !important hurts the quality of your CSS.

  • http://www.my-name-is-sam.com/blog Sam

    CSSLint is a good tool.
    Now, as every tool, it is not useful for everybody.

    HTML and JS are subject to strict rules because as you all know, the lack of efficiency in coding of those ones could lead to big troubles.
    With CSS, the problem is really different, because it’s more like personal poetry (or awful doodles).
    There are multiple ways to code CSS, it depends of the project, of the developer, of the amount of time you have to do it, etc… And it also depends of the way you learnt to work with CSS.

    In the end, CSSLint is a script and because of that, it doesn’t know the external conditions that leads to the code it analyzes.

    However, it’s a really useful for those who want to touch Perfection, and for those who just want to improve their skills.
    If you are a padawan or a jedi, it’s still very useful to confront your work to its failures or weaknesses and to learn where it came from, and how you could resolve them.
    Maybe it’ll not serve for the project you currently work on, but for the next one…

    It’s, hum, learning, I guess :)

  • http://vnsmartphone.com/ JonePee

    “Don’t use !important” ==> Do not use IE or all of the browsers

    • Mike Hopley

      Eh? How does that follow?

      If you’re talking about the !important IE6 CSS hack, then just use a better hack. Why would you want to mess up your specificity with !important in order to hack IE? Yahoo recommends the * and _ hacks:

      p {
      color: black;
      *color: blue: /* IE7 and below */
      _color: red; /* IE6 and below */
      }

      Here, IE6 will get red paragraphs; IE7 will get blue; and all other browsers will get black. These hacks are particularly suitable for OOCSS, because they don’t affect specificity.

      (Cue “Oh noes, it doesn’t validate!”…)

  • http://www.zoranperin.com Zoran

    Have to say that this tool is nice, but is is relevant in any way? Hm … that’s a question.

    Half of “do not” should be addressed to designers, so if designers wouldn’t use different font styles for different page sections, I guess coders wouldn’t be forced to use many H-tag instances.

    Further, why should for the hell sake someone in 2011 care about IE6 or older versions???

    About “!important” … there are many situations that you have to use it to override inheritance or browser defaults … so this is absolute nonsense.

    Adjoing is one of the greatest forces of CSS, so it gives you a chance to better handle elements … so I don’t see why is this wrong.

    Using classes instead od id’s have sense, especially when developing large scale website, so it is easier to lean to classes and reuse styles instead of writting it over and over again.

    However it is good to have testing tool because it will always help you to make your code better

    • Mike Hopley


      “if designers wouldn’t use different font styles for different page sections, I guess coders wouldn’t be forced to use many H-tag instances.”

      You’re right that sane code starts from a sane design, but that’s not the issue that CSS-Lint is concerned with here.

      Even when you *design* site-wide headings, the CSS code often duplicates these styles across multpile locations (h2 {}, #foo h2{}, #bar h2{}…). For example, you want h2′s in the sidebar to look smaller, so you apply the normal h3 styles to #sidebar h2. Your code now looks like this:

      h2 { … }
      h3, #sidebar h2 { … }

      …which looks okay for now, but it soon gets troublesome as you add more exceptions. And what happens when you want to use the normal h2 style in a different part of the sidebar? This happens:

      h2, #sidebar .aside h2 { … }
      h3, #sidebar h2 { … }

      You can see where this is going.


      “About “!important” … there are many situations that you have to use it to override inheritance or browser defaults … so this is absolute nonsense.”

      Why would you need it to override browser defaults (that’s what reset stylesheets are for)?

      As for inheritance problems: that’s something OOCSS solves. You don’t need to hack with !important when your CSS has a well-organised modular structure.


      “Further, why should for the hell sake someone in 2011 care about IE6 or older versions???”

      Because some websites still have a large market of IE6 users. For example, if your business has a Chinese website, then you can expect 34% of visitors to be using IE6 [ http://www.ie6countdown.com/ ].

      • http://www.zoranperin.com Zoran

        Yeah, but if you wanna keep H-tag to be semantic and logical, you need to use it in sidebars, right? So what is your choice but to add a class to specific ones or to target them with parent > child method.

        Reg. !important … if you ever build some nested menu (ul li ul li ul li thing) and have to have different styling among levels (parents, children) you were forcing using !Important to achive something.

        Reg. chinese market … to be honest, they refuse giant like Google and Facebook …. so I don’t think that any site I could do would be more important than 2 I mentioned. You cannot make it working the same on all browsers and that’s the trick … that is why browsers are getting modern and better.

  • http://www.coljung.com Pablinho

    Gotta agree with most of your points.

    We, as developers have to start pushing forward and try to leave older browsers like IE6 aside.

    Also, after 4 years developing sites, I don’t feel like other people telling me what i should or should not be doing with my code.

    • Mike Hopley

      For the headings, the OOCSS approach is to add a class:

      h3, .h3 { … }

      If you want the sidebar h2 to look like an h3, then you add the h3 class in the HTML.

      As for IE6: the decision to drop (or reduce) support should be based on the business, not on a web developer’s agenda.

      Remember you can always deselect the “adjoining classes” rule if you are not supporting IE6.


      Reg. !important … if you ever build some nested menu (ul li ul li ul li thing) and have to have different styling among levels (parents, children) you were forcing using !Important to achive something.

      I don’t understand why you need !important here. If you needed additional control, the OOCSS approach would be to add a class.

      Just because you’ve always used !important, doesn’t mean it’s the only way!


      Also, after 4 years developing sites, I don’t feel like other people telling me what i should or should not be doing with my code.

      You’re free to ignore their advice. It’s not like Nicole is personally harrassing you to mend your wicked ways. ;-)

      Now there’s a thought: how about black-belt Nicholas Zakas beating up recalcitrant web developers? Performance evangelism through the medium of kick-ass violence…

      My attitude is that I’m more likely to learn something by considering alternative views with an open mind. But after an unprecedented *four whole years* experience, I guess you know everything already. :p

  • http://www.github.com/dotink/inKLing Matthew J. Sahagian

    A useless tool which amounts to little more than “suggestions for extensible CSS”, and poor ones at that. Let me get this straight, the author of the tool is suggesting I create a class called “float” in order to float elements? Presumably I should also create classes such as “red_border” to apply red borders to elements, and perhaps just “border_medium” and “border_thin” for various sizes… then when all is said and done, when I want to change the appearance of my site I have to go into my markup and add/remove classes rather than going into my CSS where my presentation belongs.

    If I have a sidebar which is floated left, and I make a class called “float” with float: left; what happens when I want to float the element right without floating every other left floating element to the right?

    In my opinion this tool and the suggestions are failing to properly separate concerns.

  • Mike Hopley

    “Let me get this straight, the author of the tool is suggesting I create a class called “float” in order to float elements?”

    No. You’ve got it bent, not straight. ;-) OOCSS *does not* recommend stupid classes like “.float” or “.border_thin”.

    OOCSS recommends abstracting common layout code, so that you don’t write the same CSS over and over. In the case of floats, this means two things:

    1) Using a grid system for layout (e.g. OOCSS grids, YUI grids, Blueprint, 960…)
    2) Creating reusable content modules such as media blocks (an image floated beside some text)

    Classes such as “.floatLeft” and “.red_border” are far too granular. An essential part of CSS architecture is getting the right level of granularity.

    • http://www.github.com/dotink/inKSpot Matthew J. Sahagian

      While “Abstracting common layout code” is a pleasant sounding euphemism, I don’t see how this changes the core issue. The limit is 10 floats according to this article… any moderately complex design would require more than this in heartbeat even with perhaps the ideal abstraction.

      With regards to grid systems, I have addressed them in comments elsewhere, particularly with regards to the 960gs on this site. Grid systems result in the same issue because grid_16 or similar, is just a nice way of saying width_(16*column_width). Grid systems are inherently granular in their class naming and do not resolve the issue of having to edit class names in order to change the presentation.

      On the contrary, one of the things suggested against by this utility, DOES resolve that issue. For example .torso > .primary.section vs. .torso > .secondary.section. So let’s say that’s a simple two section layout, which is initially 500 for the first section and 460 for the second section. And let’s say I decide to make it even… using a grid system, I have to change my markup, changing the class of grid_x to grid_y, where y is the new width in column multiples and x is the old. Using multiple classes allows me to abstract the common properties of sections, while using specific multi-class selectors for things like width: xxx, float: left, and float: right.

      Grid systems have, as of late, attempted to promote the idea of custom class names or “aliases” for various grids where the properties of such a grid are then incorporated into the more semantic class name… this then requires something similar to LESS compilation or a middle layer to “compile” the stylesheet in some manner. Without that layer, it simply doesn’t resolve the issue completely.

      There’s a simple correlation between the level of abstraction and the reduction of separation of concerns. The more abstract a class, the more commonly it is used to achieve a more specific function. The extent to which this occurs will be the extent to which you now have to concern yourself with editing class names in markup in order to edit presentation without screwing up the other areas which use the same abstract class names. The alternative is simply using a more specific selector to override the abstraction — in which case the abstraction itself fails to be useful, and you re-enter into the world of repeating such rules anyhow.

      Re-usable content modules are great, but they simply do not address the arbitrary nonsensical limitation imposed by this particular rule of CSSLint. Such limitations, even if mere suggestions, can only make sense when determined in a context and design sensitive situation. CSSLint cannot possibly know the complexity of the data being presented, or the overall design.

      Aside from syntax and perhaps the vendor prefix stuff, the remainder of the rules can be handled at a much higher level… for example, simply saying “We won’t use more than 1-2 webfonts” on a site. This should be something recognized in the consistency of the design anyhow, and is really irrelevant to CSS. If a designer designs a site with 5 different fonts, in all liklihood they should be fired… or shot… or both.

      A number of other rules are better left simply to compression engines… not for the dev writing the human readable CSS.

  • Mike Hopley

    “Grid systems are inherently granular in their class naming and do not resolve the issue of having to edit class names in order to change the presentation.”

    I think this is where our viewpoints differ.

    You’re seeing grid systems as a problem, because you have to edit the HTML to change layout. I’m seeing grid systems as a solution, because they make layout robust and reusable.

    Grid systems are not overly granular. Classes such as “grid1of3″ are far less granular than “thinRedBorder”.

    The OOCSS philosophy is fundamentally based on allowing some “non-semantic” classes in the markup. If you’re still dreaming of 100% non-presentational HTML, then OOCSS definitely isn’t for you.

    There is a relationship between HTML “purity” and CSS complexity. Trying to keep your HTML spotless makes your CSS convoluted. Equally, going to the other extreme (tonnes of classes on every element) makes your HTML a nightmare.

    OOCSS tries to hit the sweet spot between perfect HTML and perfect CSS. The relationship is not linear. Allowing a small amount of “presentational markup” into your HTML can make your CSS much better — and much smaller too, which is important because CSS blocks progressive rendering.

    • http://www.github.com/dotink/inKLing Matthew J. Sahagian

      “You’re seeing grid systems as a problem, because you have to edit the HTML to change layout.”

      Yes.

      “The OOCSS philosophy is fundamentally based on allowing some “non-semantic” classes in the markup. If you’re still dreaming of 100% non-presentational HTML, then OOCSS definitely isn’t for you.”

      I don’t dream of 100% non-presentational HTML, I practice it. WIth regards to “OOCSS” philosophy, I’m not sure who defines that overall philosophy, but I see no conflict between 100% non-presentational and what I would consider OOCSS to be, quite the contrary, I would see them very much in line with one another. The trick, of course is having the proper level of abstraction and a proper concept of what should/shouldn’t constitute and object + a very good concept of inheritance.

      I pointed out the dichotomy of abstraction vs. separation of concerns — it’s not about abandoning abstraction, it’s about having the right level of it. I would say a GOOD rule which should be added to CSSLint should be something along the lines of ensuring no selector of broad (let’s say, that of a single independent class selector) specificity contains less than 3 rules.

      “OOCSS tries to hit the sweet spot between perfect HTML and perfect CSS.”

      Ok, but this can be achieved in the manner which I have already laid down and I have yet to see a proper defense of why limiting floats to 10 actually promotes the discovery of this sweet spot.

  • http://www.nczonline.net/ Nicholas C. Zakas

    As one of the creators of CSS Lint, I’m glad that there’s this level of discussion around the tool. To clarify some of the confusion around rules, they are all based on two very important goals: performance and maintainability. We know that we need to get more documentation explaining the rules, as the short paragraphs that we have just don’t provide enough context for the problems. We’re actively working on that.

    Another thing I’d like to point out: you can turn off any rule you disagree with. We’re not trying to force you to write CSS in any particular way, we’re just trying to show you patterns that we’ve found are problematic in our experience on small and large web applications. While some of the rules are based on OO-CSS, it is inaccurate to say that they all are. Many of the rules find very basic problems, such as syntax errors or duplicate property definitions. In fact, if you just want syntax checking, you can turn off all the rules.

    The most important thing to remember about CSS Lint is that it’s open source. There are a lot of ways for you to contribute. Since the initial release, we’ve removed rules where people found problems, modified rules based on user feedback, and even introduced rules created by others. If you have suggestions for improving the tool in any way, you can email the mailing list at css-lint@googlegroups.com or file an issue at http://github.com/stubbornella/csslint/issues. We want to hear from you, and we hope you’ll join us in making this a tool that benefits the web community as a whole.

  • http://www.nicolas-hoffmann.net/ Nico

    I can’t understand the rule “don’t use ID” !

    - Id’s are useful for hyperlinks, example : href=”meowww.html#id”,
    - they allow to have better performances for Jquery selectors,
    - and if you maintain CSS files, you are sure that it is unique in the website.

    This rule makes no sense for a well-structured integration.

    • Mike Hopley

      The rule isn’t “don’t use IDs in your markup or javascript”; it’s “don’t use IDs in [CSS] selectors”.

      From the OOCSS FAQ:

      “On the other hand, IDs are great for linking and JS hooks. Put them in the HTML, just don’t use them for styles.”

  • http://gregpettit.ca Greg

    While I also disagree with some of the rules (and had a round of whining on Twitter), the main thing that gets my fur up is simply the way the errors and/or warnings are presented. If this layer is being improved (as Nicholas comments above), I don’t see how a quick run-through could be anything but helpful. Even in the middle of my whining and ignoring warnings for my first linting (this was before there were checkboxes to disable certain rules) I found a few nice catches that I was able to use to improve my CSS.

    Anyhow, back to the point– in cases where the warnings result from “the authors think this is a good or even the best practice,” it would be helpful if the warning text didn’t imply, “you’re doing it wrong” but rather implied a tone of “hey, we think we have a suggestion that might help you here!”

  • http://www.maxmonastyrev.co.nz Max

    In terms of specificity, using ID’s makes sense, but should I then use classes instead of ID’s, its confusing!