12 Common CSS Mistakes Web Developers Make

Sep 8 2010 by Max Luzuriaga | 105 Comments

12 Common CSS Mistakes Web Developers Make

Let’s get real for a second here. As far as web languages go, CSS is arguably the simplest. I mean, really, what could be easier than a simple list of properties affecting an element? And the syntax is almost like written English. Want to change the font size? There’s a font-size CSS property. How about the color? There’s the color property.

But despite its deceptively easy exterior, CSS is one complicated system, especially when you’re doing it in a professional, high-scale, high-performance level. The sheer number of ways to select an element is amazing; not to mention the number of properties you can apply to that selected element set and then how presentation changes when you’re talking about supporting multiple browsers and layout engines.

It’s easy to get tripped up with CSS. Here are some common CSS mistakes we all make.

1. Not Using a Proper CSS Reset

Web browsers are our fickle friends. Their inconsistencies can make any developer want to tear their hair out. But at the end of the day, they’re what will present your website, so you better do what you have to do to please them.

One of the sillier things browsers do is provide default styling for HTML elements. I suppose you can’t really blame them: what if a "webmaster" chose not to style their page? There has to be a fallback mechanism for people who choose not to use CSS.

In any case, there’s rarely a case of two browsers providing identical default styling, so the only real way to make sure your styles are effective is to use a CSS reset.

What a CSS reset entails is resetting (or, rather, setting) all the styles of all the HTML elements to a predictable baseline value. The beauty of this is that once you include a CSS reset effectively, you can style all the elements on your page as if they were all the same to start with. It’s a blank slate, really.

There are many CSS reset codebases on the web that you can incorporate into your work. I personally use a modified version of the popular Eric Meyer reset and Six Revisions uses a modified version of YUI Reset CSS. You can also build your own reset if you think it would work better.

What many of us do is utilizing a simple universal selector margin/padding reset.

* { margin:0; padding:0; }

Though this works, it’s not a full reset. You also need to reset, for example, borders, underlines, and colors of elements like list items, links, and tables so that you don’t run into unexpected inconsistencies between web browsers.

Learn more about resetting your styles via this guide: Resetting Your Styles with CSS Reset.

2. Over-Qualifying Selectors

Being overly specific when selecting elements to style is not good practice. The following selector is a perfect example of what I’m talking about:

ul#navigation li a { ... }

Typically the structure of a primary navigation list is a <ul> (usually with an ID like #nav or #navigation) then a few list items (<li>) inside of it, each with its own <a> tag inside it that links to other pages. This HTML structure is perfectly correct, but the CSS selector is really what I’m worried about.

First things first: There’s no reason for the ul before #navigation as an ID is already the most specific selector. Also, you don’t have to put li in the selector syntax because all the a elements inside the navigation are inside list items, so there’s no reason for that bit of specificity.

Thus, you can condense that selector as:

#navigation a { ... }

This is an overly simplistic example because you might have nested list items that you want to style differently (i.e. #navigation li a is different from #navigation li ul li a); but if you don’t, then there’s no need for the excessive specificity.

I also want to talk about the need for an ID in this situation. Let’s assume for a minute that this navigation list is inside a header div (#header). Let us also assume that you will have no other unordered list in the header besides the navigation list. If that is the case, we can even remove the ID from the unordered list in our HTML markup, and then we can select it in CSS as such:

#header ul a { ... }

Here’s what I want you to take away from this example: Always write your CSS selectors with the very minimum level of specificity necessary for it to work. Including all that extra fluff may make it look more safe and precise, but when it comes to CSS selectors, there are only two levels of specificity: specific, and not specific enough.

3. Not Using Shorthand Properties

Take a look at the following property list:

#selector {
  margin-top: 50px;
  margin-right: 0;
  margin-bottom: 50px;
  margin-left 0;
}

What is wrong with this picture? I hope that alarm bells are ringing in your head as you notice how much we’re repeating ourselves.

Fortunately, there is a solution, and it’s using CSS shorthand properties. The following has the same effect as the above style declaration, but we’ve reduced our code by three lines.

#selector {
  margin: 50px 0;
}

Check out this list of properties that deals with font styles:

font-family: Helvetica;
font-size: 14px;
font-weight: bold;
line-height: 1.5;

We can condense all that into one line:

font: bold 14px/1.5 Helvetica;

We can also do this for background properties. The following:

background-image: url(background.png);
background-repeat: repeat-y;
background-position: center top;

Can be written in shorthand CSS as such:

background: url(background.png) repeat-y center top;

Using shorthand CSS improves efficiency and makes it easier to maintain our code. For more information on CSS shorthand properties, check out this cheatsheet of CSS shorthand properties.

4. Using 0px instead of 0

Say you want to add a 20px margin to the bottom of an element. You might use something like this:

#selector { margin: 20px 0px 20px 0px; }

Don’t. This is excessive. There’s no need to include the px after 0. While this may seem like I’m nitpicking and that it may not seem like much, when you’re working with a huge file, removing all those superfluous px can reduce the size of your file (which is never a bad thing).

5. Using Color Names Instead of Hexadecimal

Declaring red for color values is the lazy man’s #FF0000. By saying:

color: red;

You’re essentially saying that the browser should display what it thinks red is. If you’ve learned anything from making stuff function correctly in all browsers — and the hours of frustration you’ve accumulated because of a stupid list-bullet misalignment that can only be seen in IE7 — it’s that you should never let the browser decide how to display your web pages.

Instead, you should go to the effort to find the actual hex value for the color you’re trying to use. That way, you can make sure it’s the same color displayed across all browsers. You can use a color cheatsheet that provides a preview and the hex value of a color.

This may seem trivial, but when it comes to CSS, it’s the tiny things that often lead to the big gotchas.

6. Redundant Selectors

My process for writing styles is to start with all the typography, and then work on the structure, and finally on styling all the colors and backgrounds. That’s what works for me. Since I don’t focus on just one element at a time, I commonly find myself accidentally typing out a redundant style declaration.

I always do a final check after I’m done so that I can make sure that I haven’t repeated any selectors; and if I have, I’ll merge them. This sort of mistake is fine to make while you’re developing, but just try to make sure they don’t make it into production.

Check out this list of CSS optimizers that can help you automate the search for inefficient and redundant selectors.

7. Redundant Properties

Similar to the one above, I often find myself having to apply the same properties to multiple selectors. This could be styling an <h5> in the header to look exactly like the <h6> in the footer, making the <pre>‘s and <blockquote>‘s the same size, or any number of things in between.

In the final review of my CSS, I will look to make sure that I haven’t repeated too many properties. For example, if I see two selectors doing the same thing, such as this:

#selector-1 {
  font-style: italic;
  color: #e7e7e7;
  margin: 5px;
  padding: 20px
}
.selector-2 {
  font-style: italic;
  color: #e7e7e7;
  margin: 5px;
  padding: 20px
}

I will combine them, with the selectors separated by a comma (,):

#selector-1, .selector-2 {
  font-style: italic;
  color: #e7e7e7;
  margin: 5px;
  padding: 20px
}

I hope you’re seeing the trend here: Try to be as terse and as efficient as possible. It pays dividends in maintenance time and page-load speed.

8. Not Providing Fallback Fonts

In a perfect world, every computer would always have every font you would ever want to use installed. Unfortunately, we don’t live in a perfect world. @font-face aside, web designers are pretty much limited to the few so called web-safe fonts (e.g. Arial, Georgia, serif, etc.).

There is a plus side, though. You can still use fonts like Helvetica that aren’t necessarily installed on every computer. The secret lies in font stacks.

Font stacks are a way for developers to provide fallback fonts for the browser to display if the user doesn’t have the preferred font installed.

For example:

#selector {
  font-family: Helvetica;
}

Can be expanded with fallback fonts as such:

#selector {
  font-family: Helvetica, Arial, sans-serif;
}

Now, if the user doesn’t have Helvetica, they can see your site in Arial, and if that doesn’t work, it’ll just default to any sans-serif font installed.

By defining fallback fonts, you gain more control as to how your web pages are rendered.

9. Unnecessary Whitespace

When it comes to trying to reduce your CSS file sizes for performance, every space counts. When you’re developing, it’s OK to format your code in the way that you’re comfortable with. However, there is absolutely no reason not to take out excess characters (a process known as minification) when you actually push your project onto the web where the size of your files really counts.

Too many developers simply don’t minify their files before launching their websites, and I think that’s a huge mistake. Although it may not feel like it makes much of a difference, when you have huge CSS files, it can improve your page response times.

10. Not Organizing Your CSS in a Logical Way

When you’re writing CSS, do yourself a favor and organize your code. Through comments, you can insure that the next time you come to make a change to a file you’ll still be able to navigate it.

How you choose to organize your styles is completely up to you, whatever works. I personally like to organize my styles by how the HTML that I’m styling is structured. This means that I have comments that distinguish the header, body, sidebar, and footer.

A common CSS-authoring mistake I see is people just writing up their styles as soon as they think of them. The next time you try to change something and can’t find the style declaration, you’ll be silently cursing yourself for not organizing your CSS well enough.

11. Using Only One Stylesheet for Everything

This one’s subjective, so bear with me while I give you my perspective.

I am of the belief, as are others, that it is better to split stylesheets into a few different ones for big sites for easier maintenance and for better modularity. Maybe I’ll have one for a CSS reset, one for IE-specific fixes, and so on.

By organizing CSS into disparate stylesheets, I’ll know immediately where to find a style I want to change. You can do this by importing all the stylesheets into a stylesheet like so:

@import url("reset.css");
@import url("ie.css");
@import url("typography.css");
@import url("layout.css");

Let me stress, however, that this is what works for me and many other developers. You may prefer to squeeze them all in one file, and that’s okay; there’s nothing wrong with that. But if you’re having a hard time maintaining a single file, try splitting your CSS up.

12. Not Providing a Print Stylesheet

In order to style your site on pages that will be printed, all you have to do is utilize and include a print stylesheet.

It’s as easy as:

<link rel="stylesheet" href="print.css" media="print" />

Using a stylesheet for print allows you to hide elements you don’t want printed (such as your navigation menu), reset the background color to white, provide alternative typography for paragraphs so that it’s better suited on a piece of paper, and so forth.

The important thing is that you think about how your page will look when printed. Too many people just don’t think about it, so their sites will simply print the same way you see them on the screen.

Related Content

About the Author

Max Luzuriaga is a freelance web designer (see his work on his portfolio site). He’s also a design blogger at The Design Gnome. He likes web standards and loves talking in the third person. Follow him on Twitter as @designgnome.

105 Comments

Andrew Tebbott

September 8th, 2010

Nice article Max. Very informative indeed.

Adam S

September 8th, 2010

Splitting your stylesheets into multiple just for readability is simply a bad idea and a poor tip. Each stylesheet then becomes its own http request, which is not optimal. If you want to maintain multiple sheets, minify them into one stylesheet, that way it’s one simple http stream for all styles.

Steve Pye

September 8th, 2010

Excellent article… one other thing I’ve taken to recently, to aid in readability is to adjust the tab-stop, using, effectively, a colon tab in much the same way as a decimal tab. Some people may not like this approach, and it does require a little extra fiddling to align things, but it also makes for some unique readability (although I’m not sure if the comment will show it correctly without a fixed-width font):

#selector-1 {
font-style: italic;
color: #e7e7e7;
margin: 5px;
padding: 20px
}

Andrey Shipilov

September 8th, 2010

It’s like one always does a Google website…

I’m not saying it’s a bad article (though it is), but all that “hits” will do nothing to the render-speed or readability – the browser interprets all the CSS its own way. The only thing it will help is minifying the file size, which is useless. Unless you are Google.

PS. There are really more than just that 12 errors coders make.

Steve Pye

September 8th, 2010

Yeah, it didn’t… anyway, try lining up all the colons vertically, so, ragged left and ragged right, but all of the property values are aligned to each other, and only one space away from the property name.

Luke Jones

September 8th, 2010

Good but I wouldn’t recommend using the short-hand font:; property. Even many CSS gurus refrain from using that. It’s just awful.

Bri Manning

September 8th, 2010

For #9 and #11 – I would say you can definitely ignore those until you go into production (and your test environment). You can easily concatenate those separate files into one and then minify them to remove whitespace.

When actually developing, however, I would say there is absolutely no problem in ignoring those considerations.

Chris Lentz

September 8th, 2010

Great list. I am guilty of 2 of those.

PJP

September 8th, 2010

Hi, nice article, great tips!
However, I’ll mention that using @import is not recommended by Steve Souders in his High Performance Web Sites book as it can cause rendering issues (not the same order every time) or FOUCs.
I didn’t verify this by myself, but I never user @import cause it adds complexity (in my case) in the minifying process.

ArmNo

September 8th, 2010

Very useful article.
I never remember shorthand for font properties. (too long for me)
but my IDE saves my life!

Thanks for sharing.

Dave

September 8th, 2010

Who are you to call these mistakes? They aren’t mistakes at all. You’ve just written a list of suggestions and want to make it sound dramatic. Many sites could disobey all these points and still be perfectly valid and display correctly in their target browsers.

John G

September 8th, 2010

This is so true. I’m very lazy about using a reset. I know I need to really get it together in that regard. It makes things so much easier when you start out with one.

Sam

September 8th, 2010

not that I am finding fault for the sake of it but I have a different take on some of the points raised here and reason explained alongside

point1 using ‘*’ for reset is slow and applies to elements you don’t want to universally select eg inputs. When reseting be selective don’t tar all with same brush.

point11 is negated by point10. How often you you change the reset? not much. @import is super slow. If css is kept maintainable with markers as described by NatBat then you can reduce the number of files and still be able to find what you need. I find the more files you have the harder maintence becomes (like a horror film with sequels)

if following advice from point11 having a minification process that Combines & Concats the many and various in to one is good

point12 can exist ina single master sheet – reduces http requests. Print Stylesheets are always downloaded – one sheet to style them all – see Zoe’s post below

point3 Nate Koechley (yahoo) “Avoid using the font: shorthand because it is parsed inconsistently across browsers”

http://natbat.net/2008/Sep/28/css-systems/
http://zomigi.com/blog/maintainable-efficient-css/

NikoLang

September 8th, 2010

Nice Article. I Agree to every Point, except Number 11. Of course you might split your CSS-files as much as you like in your development environment. But because of performance reasons, you should merge them again for your live system. Loading one big file is faster than loading many small files. You will gain much more speed with that than doing small optimizations like removing whitespaces.

Stuart

September 8th, 2010

Nice list. Couple of comments:

5. Using Color Names Instead of Hexadecimal
If you have something like #CCFF00 you can reduce to #CF0.

11. Using Only One Stylesheet for Everything
The downside with using several external stylesheets is that you increase the number of HTTP requests. Reducing HTTP requests is the key way of improving a site’s initial load times, according to Rule 1 at http://stevesouders.com/hpws/rules.php.

Actually, I’m not sure whether @import actually does generate extra requests – but if it does, it’s not a lot of work to have separate CSS files while developing, only to combine them prior to roll-out.

Alex

September 8th, 2010

To produce a valid CSS you have to specify the unit.
It can be px, em, %…
It’s not a good idea to create an invalid CSS just to save a few bytes.

Johnny

September 8th, 2010

Full resets seem like a waste of time to me. Also the whitespace thing can help make your CSS more readable and is arguable.

Otherwise, pretty good tips for beginners :)

krike

September 8th, 2010

Glad I’m not making that many mistakes :)

Patrik

September 8th, 2010

Good sum-up I can agree on most of it although I cannot agree on splitting up the css into several files and css reset. Both of them adds unnecessary load time and thus latency.

CSS reset adds rules you might not need at all and those you do need will often just get overwritten anyway. Be careful not to reset things that should not be reseted. For example consider a user who use the keyboard to navigate the site, an outline might come handy here.

Maybe this is just something that one developer think is good and another think is bad. On the other hand, if you are a good developer then you should know of the browser inconsistencies and wouldn’t need to reset. To say that it is a mistake not to use reset is a bold statement. I see it as a thing for the novice developer who really doesn’t understand how the browsers works.

Arthur Kay

September 8th, 2010

I have to seriously disagree with you on points #1 and #11.

Regarding CSS resets, I think they can be useful. But I see too many designers/developers using them when they aren’t necessary. You talk about minifying CSS and reducing whitespace, but in many cases the CSS resets are simply redundant.

And regarding multiple CSS stylesheets, again you’re negating your earlier argument about CSS whitespace/minification. I would agree that multiple stylesheets and whitespace help organize code… but if you need that much code, you should condense it to a single minified CSS file when deploying the website.

One last thing… I do agree with you on the print stylesheet, but shouldn’t we be designing websites that print well to begin with? I think having black text on a white background is about the only serious consideration I can think of.

Jesse

September 8th, 2010

For the most part, everything here makes sense, but I think the argument for #2 (Over-Qualifying Selectors) is weak. The point is made that the specificity isn’t needed, and I agree, but there isn’t a good reason given. The section ends with “…but when it comes to CSS selectors, there are only two levels of specificity: specific, and not specific enough,” but the argument presented is that the selector shown was too specific so that doesn’t really add up. If “specific and not specific enough” are the only two levels for a selector, one would infer that “not specific enough” is a negative (just based on the wording) and that one should aim to be specific…yet not too specific…but according to the author that level of specificity doesn’t exist so how can you argue that something is too specific? Wouldn’t it just be “specific” which is implied to be preferred to “not specific enough”? I still agree that more generic selectors should be used as it allows for more reuse and less duplication, but that argument isn’t made here. The author simply states that they should be less specific and never really gives a reason that makes sense.

Daniel

September 8th, 2010

#4: one can simplify left-right amount (eg: 20px 0 20px 0) to 20px 0; no need for repetition :)

Amber Weinberg

September 8th, 2010

I disagree with using multiple stylesheets. It ends up in extra http requests and the multiple sheets get confusing and actually make your CSS longer, since you have to separate the same rule into 2+ sheets.

Jérôme Coupé

September 8th, 2010

Nice list.

About using multiple imports (instead of links) and many other tricks of the trade as far as CSS is concerned, I recommend the following post and attached slides by Zoe Mickley Gillenwater: http://zomigi.com/blog/maintainable-efficient-css/

peter

September 8th, 2010

I agree with most, completely disagree with #2.

There’s really nothing wrong with being specifics with your DOM. Especially if you have complex documents that requires you to style specific elements without grabbing everything within the parent DOM.

jdirt

September 8th, 2010

A lot of these tips are either wrong or wrongheaded. Use with caution.

Misel

September 8th, 2010

Most of the stuff can be solved with code. Do you know any programs that would optimize your CSS in the way described here?

Josh

September 8th, 2010

Nice list, but I must disagree with the specificity point you made, when using many CMS applications like Drupal its definitely necessary to be as specific as you can, as the way that plugins are developed, you don’t know what code they might be using and what selectors, so by being excessively specific you ensure not mixing of styles. Overall all great advice though.

Matt Hill

September 8th, 2010

@Alex: That’s not true at all. Zero values should have no units on them; after all, you can’t have Zero pixels or Zero centimetres!

BooshCreations

September 8th, 2010

@Alex Not when it comes to values that are 0

I don’t agree with having multiple css files, everything can easily be maintained in one file. I see a lot of sites that use a seperate style sheet for ie, which is not needed if you have styled things up properly in the first place.

Jeremy Carlson

September 8th, 2010

I agree with the comments about #11. Plus, I don’t think the minifier allows @import. You can have several sheets, but not imported into one.

Ben Briggs

September 8th, 2010

Was point 5 included to pad out the number of bullet points in the article? Using colour names is perfectly valid, and in your example even the shorthand hex is 1 character longer than the named value (#ff0000 = #f00 = red). You would have thought that when the previous point was nitpicking about using 0px because it’s two characters longer than 0, then you would be nitpicking about using named colours instead of hexadecimal because it may or may not be shorter.

Does it matter?

Colour values display consistently across browsers; the only reason that they may differ from computer to computer is if the monitor’s colour settings are different. There is even a list of the ones that are compatible with all browsers!

http://www.w3schools.com/css/css_colornames.asp

Number 11 is also going to slow your site down because of the increased number of HTTP requests; doing that just to make your code look pretty and organised into neat little sections won’t benefit your users. Many studies show that increased page load times make a user less likely to carry on looking at your website.

Young

September 8th, 2010

Wow lots of negativity here.

If you ask me, as long as it validates, it’s all preference. We all struggle to balance bandwidth and usability, but I prefer the latter. The bigger the site, the more attractive multiple stylesheets start to look.

I think this was a successful article. Definitely not “mistakes.” I’d say suggestions.

Honestly, when we’ve come so far with computing power, should we really worry about a few more bytes transferring? I have a hard time believing it’s really gonna matter, unless your site has 100,000 visitors at a time – and if that’s the case you could probably afford the computing power to handle it!

Fernando Val

September 8th, 2010

Nice article.
I approve this test. 9 over 12… :D

I’ll try to refine those 3 aspects.

RussellUresti

September 8th, 2010

There’s a bit of mixed signals in here; I’m not sure if you’re talking about developing/maintaining CSS or if you’re talking about CSS that’s being pushed live. Number 9 mentions minifying CSS, which is great for CSS that’s pushed live, but number 11 mentions using multiple stylesheets, which is horrible for what’s been pushed live — each of those files is an additional HTTP request, so each one times up a connection that could be used to download other resources and load the page faster.

Additionally, multiple stylesheets will most likely mean redundant selectors (violation of number 6). For example, in layout.css you may have something like “#nav a { display: block; }” but in typography.css you’d also have “#nav a { font: 14px/18px Helvetica, Arial, sans-serif;”. So you have the same selector in multiple CSS files.

I agree that separating them out can be good for organization, but the final product should be a single file.

I also disagree with number 4. If you use something like “padding: 0″ and don’t clarify the measurement type the next developer who comes along may not know how to adjust this correctly if you now need additional padding. Were you using ems? pixels? points? percentages? It probably wouldn’t take too long to figure out, but it’s unnecessary work. Brevity is good, but not at the cost of clarity. I always use a unit of measurement with my 0 values, attaching whatever measurement I would append if there was a real value. So, if I were doing a fluid design I would put 0%, if I were basing everything on the typography I might do 0em, etc. Could you remove this when you package up and minify the file for push to live? Sure, but the original development source should indicate these values.

Eric Carlisle

September 8th, 2010

Max,
Another perk about #11. If you @import all of your CSS into a main.css, the page performance will be much better than putting a lot of tags in the HTML.

Pedro

September 8th, 2010

Using something like “#header ul a { … }” takes a lot of processing. The browser will collect all the “a” tags in the page. Then it will collect all the “ul” tags over the page. Finally, from all the collected tags, it will pick the “a” that is inside of a “ul” that is inside the #header. Imagine the processing and the time needed when this happens thousands of times on one stylesheet. Its better to always give an “id” to an element, or a “class” atribute, but preferably an id. Nothing is simpler and works a lot better.
The “reset” thing, I hate that stuff. Take the above logic and apply it to all the elements on the page, before the page is viewed by the user. Imagine how many times the browser has to read the stylesheet from top to bottom to collect all the tags before even choosing them. A waist of time.

Adam V

September 8th, 2010

Using shorthand properties can be EXCEEDINGLY risky. You should ONLY use them if you’re actually setting ALL the parts of the shorthand. If you don’t, you run the risk of unexpected consequences or overdoing your code. Consider the following:

.dialog{
background: url(dialog-background.png) no-repeat left middle;
}
.alert {
background: #00aaaa url(alert-background.png);
}
.error {
background: url(alert-background.png);
}

when applied to the following markup:

Boo!

in this instance, your background will be your error image tiled across the entire dialog box rather than just the icon in the specific place it should be.

You can avoid the problem with:

.dialog{
background: initial url(dialog-background.png) no-repeat left middle;
}
.alert {
background: #00aaaa url(alert-background.png) no-repeat left middle;
}
.error {
background: #00aaaa url(alert-background.png) no-repeat left middle;
}

but that is very inefficient and no _necessarily what you want, especially if you plan to resuse these bits elsewhere. A better solution would be:

.dialog{
background-image:url(dialog-background.png)
background-repeat: no-repeat;
background-position: left middle;
}
.alert {
background-color: #00aaaa;
background-image: url(alert-background.png);
}
.error {
background-image: url(alert-background.png);
}

You could argue that the .dialog _could_ have the shortcut but since I do not want to excplictly state what the background color is for it, I rather be explicit about the fact.

James Godwin

September 8th, 2010

Great tips, thanks. I’m a massive fan of blueprintcss and especially it’s reset file.

Ahmad Alfy

September 8th, 2010

Used to do those when I started 5 years ago … lol

TomkOx

September 8th, 2010

Make your site turbo charged in speed! 1: Split everything into one single html file (as much as possible: html,css,js,images); 2: Serve site with enabled cache, cache and cache (as much and for a long time as possible); 3: Serve with gzip compression; 4: Do not trust in all those articles about “web-dev” on the Web ;)

TomkOx

September 8th, 2010

… and use sRGB profile for images (with calibrated gamma to 2.2), then optimize all the PNGs you use (for example: with imageOptim) on your sites.

TomkOx

September 8th, 2010

… and :) (also important) use UTF-8 encoding (it is just easier).

Max Luzuriaga

September 8th, 2010

Wow. Sorry, I didn’t realize this was going to turn out to be such a controversial post! It seems that most of the comments are addressed to #11 first, so let me address that.

I believe that the extra HTTP requests (although using @import solves this problem) are an okay price to pay for the convenience and organized nature of using multiple files. I wasn’t telling you that you have to change your coding style to fit my opinions. They are, after all, my opinions. You can all choose, if you want, to shove every bit of CSS in your project into one file, and I couldn’t tell you to stop. My mind works in such a way that I prefer having all those extra files in place of HTTP requests (although again, I don’t think that’s an issue with @import).

As far as shorthand properties: I’ve never heard of a browser (except maybe IE6) not supporting the shorthand font property. I like seeing all the font-related properties on one line, and it saves a ton of space.

I guess there are places where you would have to be overly specific in your selectors, but as a general rule I try to make them the least specific that is still specific enough.

JT

September 8th, 2010

I think #11 can be taken as personal preference like you say. The extra requests may be undesirable on a high bandwidth site with tons of visitors but most sites can get away with it.

I rather keep my css files as flat as possible so will usually have 2 files max. The first being a reset followed by basic layout and the second everything else. Depends on the complexity of the site to be honest.

A third may come in to play if there’s a section of the site so different from the rest it warrants one.

firebug tells me exactly where to find something if I need to anyway.

One thing to bear in mind though is that more css files can lead to excessive selectors and unnecessary duplications if you’re not careful.

You’ve made some good points here and I think some people should realise they won’t all apply in certain situations and just ignore the ones they don’t like.

Dallas Clark

September 8th, 2010

I was about to bring up point #11 but that’s already mentioned many times before. @Max I believe you should always write for success, you never know if your website or your client’s website is going to be really successful.

I’ve been in the situation before (years ago) where I thought I can just do it this simple way and was bitten hard on the backside when the whole site was running really slow. Performance always matters !

Craig

September 8th, 2010

Great tips to help with good coding practice, Thanks!

Mike A.

September 8th, 2010

Great list, Max. Another option is to backup the CSS files and have a compressed version for the live site. That way, if you need to go back and make changes, you can do so using the easy-to-read version… then compress it when you publish it.

Carl Walker

September 8th, 2010

Interesting to see so many opinions about CSS practices. I agree with most of them apart from the import, shorthand, removing ‘px’, and using comments.
Others have stated the problems with import and HTTP requests. Some shorthand will not work 100%, especially background ones. Many browsers require them in certain circumstances. As also stated, removing ‘px’ is not valid and you talk about minifying… Yet state to add comments. That’s a contradiction, comments should be removed during that process.

“As far as shorthand properties: I’ve never heard of a browser (except maybe IE6) not supporting the shorthand font property.”
IE6 and other older browsers are still high amongst the most used versions, due to schools or low budget offices, etc. Excluding them is just a huge mistake.

Billy

September 8th, 2010

I make a lot of these simple mistakes, definitely gotta work on that. Great article man.

Scott

September 8th, 2010

@Pedro: I don’t think that’s right (if it is then browsers are incredibly inefficient!) The process for parsing something like “#header ul a { … }” is actually: (1) the browser finds all ‘a’ tags, (2) it searches upwards through the DOM until it finds a ‘ul’ tag. Then upwards to other tags/selectors.

Caveat: With the ID selector, things probably change, the browser would likely get the ID first (since it unique and a subset of the DOM) then search within that.

Andrew

September 8th, 2010

Not a good list.

For as much as you seem to care about speed and filesize you’ve got some things horribly wrong. Setting out with the goal of using multiple stylesheets increases the number of requests that a browser needs to make on your site. For some internet connections it’s not a big deal, but if you’re on low ping connection (anything mobile) every extra request is a huge hit.

And the kind of reset you described is just bad practice. defining anything with just * makes a css check against every single element in your document – if it needs it or not. Resets aren’t required if you code correctly from the beginning, but if you must use them, consider just setting styles rather than resetting them. http://thinkvitamin.com/design/setting-rather-than-resetting-default-styling/

Andrew

September 8th, 2010

Max,
@import still makes an extra http request. There’s nothing in @import that bundles the CSS server side, so the browser still has to make a request for it.

Israel Canasa

September 8th, 2010

#11 is something that everyone should avoid. Using @import makes more http requests which slows the webpages down.

If you want to organize your code, use tools like Less.js or Sass. Less.js(github.com/cloudhead/less.js) is recommended coz it’s so easy to setup. And it has a development mode where the changes to your CSS are reflected automatically when you save the .less file. For a more integrated CSS/HTML5 development, use Flawless http://bit.ly/cfQCAF.

When deploying CSS for production, compress it and put everything in one file. For development, just use the tools I recommended.

Cheers :)

Eneza

September 8th, 2010

Guilty as charge of no. 2 and no. 7.

The no.7 I usually commit this when in a hurry!
Thanks for this, appreciated it!

Elaine

September 9th, 2010

Fantastic article, very very useful. It’s a good checklist to go through before and after you code your css and also has some great links. Thank you!

Jakub Vrana

September 9th, 2010

Point 5 about colors is FUD. Color names are strictly defined at http://www.w3.org/TR/CSS21/syndata.html#color-units and all browsers respect it.

Scott

September 9th, 2010

Some great points, glad to say I follow most of them already.

Señor Swinstead

September 9th, 2010

Another post of “here’s how I do it, you should all do it exactly like I do, just for the sake of it”

Come on, seriously, your best advice when it comes to improving our CSS is to split it into multiple stylesheets (DON’T DO IT, KIDS!), be less picky about specifying which elements we style (WHY??) and invalidating our CSS by dropping the unit specifications to save a handful of bytes (BAD IDEA).

The few bits in here that aren’t totally wrong are, however, a complete waste of time that results in doing things no better at all.

I liked the comment from the author that was like “All browsers know how to handle the ‘font’ shorthand. Except maybe IE6. But that’s not important.”

YES it is!

I have horrible fears for all these people posting “great article thanks for all the brilliant advice” and actually taking the time to implement this crap on their sites.

Agos

September 9th, 2010

Most of these are not errors!
Points 3, 4, 9 reduce size a bit, but do great damage to readability. Not good! A decent CSS compressor (which, absurdly, you didn’t mention) will do better, and you still have a readable original.
Same with @import rules, it’s useless to shave whitespace if you have 4 more HTTP requests going on.

Gavin Laking

September 9th, 2010

Also, to help construction of stylesheets, take a look at Compass and SASS. http://compass-style.org/. I use this even inside non-Ruby projects to compile my stylesheets. The syntax is simple, allows nesting (which definitely helps with organisation) and can be compressed. You can also create sheets for different browsers (I’m looking at you IE) so you can put all your hacks in one place. Hope that helps!

Elise

September 9th, 2010

I’ve never thought to include a Print Stylesheet, but I certainly will from now on. Thanks for the tips!

Ravikumar Tamada

September 9th, 2010

You explained very well. Although i am maintaining my CSS the way you suggested, but some modification needs to be added i’m going to do it right now ! thank U

Ravikumar Tamada

September 9th, 2010

You explained very well. Although i am maintaining my CSS the way you suggested, but some modification needs to be added i’m going to do it right now ! thank U

Adam

September 9th, 2010

This will clear some doubts regarding eleventh point:
http://www.stevesouders.com/blog/2009/04/09/dont-use-import/

There is a balance that needs to be find between HTTP requests and organisation of files in project.

Jeffrey Arts

September 9th, 2010

Don`t use @import (#11) cause it would slow down you website if you`ll do it like this !
To use several css files use .
Reference:
http://www.stevesouders.com/blog/2009/04/09/dont-use-import/

Peter

September 9th, 2010

Who prints out a website?
never have used media=”print”, never will

Things I would consider for print go into a .pdf

Russell Heimlich

September 9th, 2010

There are some good shorthand CSS properties and bad ones. font is a bad shorthand property because the order of the properties is irrelevant. This means you need to spend more time thinking about what properties are listed when you want to change something, an increase in cognitive load. In that case I find it easier to use the standard properties for font styles.

Here’s an example to illustrate my point http://www.russellheimlich.com/frontend-tips/css-shorthand.htm

Jacob Gube

September 9th, 2010

@Peter: My mom does! :) Sadly, she can’t print out Six Revisions properly because I also think print stylesheets are superfluous. You lose a lot of context and benefits when you print off a hyper-linked medium. That’s just my personal philosophy though. You can still print off Six Revisions pages, but I haven’t gone out of my way to make it easier by providing a print stylesheet.

Jimmie

September 9th, 2010

Regarding using mulitiple CSS files is good when you are developing but nowadays has a function that make one file in the end anyway, if you dont have a function like that then it’s not good because of the extra http requests.

Jason

September 9th, 2010

Some of these are just preferences as opposed to good practices, I’ll print out the article and circle them for you. ;)

TheAL

September 9th, 2010

As a few, or a lot, of people have no doubt already said, I’m not always a fan of resets. They have ups. They have downs. And while none of these are actually mistakes, and could be used with no real ill effect, good practices that create industry-wide standards are never bad. Nice list.

Edwin Sandoval

September 9th, 2010

I think that this post is very polemic, maybe it could be better to open a survey even though the vote of a goru should be more relevant jejeje its chaos.

Goofy

September 9th, 2010

So whitespace is bad, but abusing ASCII to make a large narcissistic spelling of your name is fine?

Max Luzuriaga

September 9th, 2010

@Peter @Jacob

The most useful thing in a print stylesheet for me is hiding unnecessary elements, AKA, things that wouldn’t have any benifit to being printed like a navigation bar.

As far as hyperlinks go, if you use a { content: ” (” attr(href) “) “; }, then you can actually display the anchor’s href after the element! I didn’t come up with that myself, but I can’t remember where I learned it. Useful trick.

Jacob Gube

September 9th, 2010

@Goofy: Looks like you had to dig hard and grasp at straws for that one. I’ll give you a 3/10 on the troll scale just because you took the time to look at the source.

Max Luzuriaga

September 9th, 2010

@Goofy

I feel like “narcissistic” is a little strong for 9 lines of code spelling my name. If it was “Max Luzuriaga is great,” then you might have a point…

simisker

September 9th, 2010

For those claiming that omitting the unit [Point 4: "Using 0px instead of 0"] is invalid CSS, here’s some bedtime reading:

http://www.w3.org/TR/CSS2/syndata.html#length-units

“After a zero length, the unit identifier is optional.”

madr

September 10th, 2010

A good list. IE stops @importing css-files when more than 60-70 file references, so don’t split too much.

When working with oocss plugins according to spec, this might be a common situation.

Myself, I rely to sass/scss/less which always results in just one minified css-file when I go to production. And I usually implement @media print {} in my master file instead of making an extra http request for print css. Sadly, few clients is willing to pay for print css these days … :/

Mike

September 10th, 2010

I remember when CSS first gained traction (that was oh ‘soooo long’ ago…maybe eight years or ten years ago…) for years everyone recommended the long-hand styling because it minimized your need for comments and figuring out which did what when changing a design.

As for separate style sheets; have you ever tried coding text separate from your layout from scratch by hand? It’s confusing and redundant; plus getting everything to harmonize becomes a chore. I mostly keep the css to four separate sheets: one for the layout and text, one for print, one for IE, and a reset sheet.

ddeja

September 10th, 2010

Well as I see most of readers have issue with number 11 of this article.

Right now I’m working on this big big project (.NET, not sure if same thing is possible in PHP or other languages) and the best thing about it is…. You have multiple css sheets for many things.

The trick is that application loads only your base file for example default.css – definitions and than 1 or 2 stylesheets specified for current view.

So at the end you get to load 2-3 small files instead of one big ass file. And the maintaince is just great.

As for smaller projects well one stylesheet is still better.

Anyway overall nice article.

Cheers.

Greg

September 11th, 2010

You don’t justify any of your positions other than to say they are faster and easier and to site a source which does the same thing.

Even “simple” short hand, requires you to memorize rules that make the code harder to read and maintain. If it’s needed for speed, then ok, lets go with harder, faster code.

Wouldn’t it be most efficient to remove all the unused CSS in the a given file? I pulled the CSS from your portfolio site which should serve as a good example of your work in practice:

“50% of CSS (estimated 5.2kB of 10.3kB) is not used by the current page.”

Greg

September 11th, 2010

“Choose over @import

tag: css

One of the previous best practices states that CSS should be at the top in order to allow for progressive rendering.

In IE @import behaves the same as using at the bottom of the page, so it’s best not to use it.”

Source: http://developer.yahoo.com/performance/rules.html

Also note, no where in the entire document do they say use CSS short hand to create faster page loading. And the very first point is: “Minimize HTTP Requests”.

AceeBaBa

September 11th, 2010

Yes i Also disagree with using multiple style sheets. That Need extra http requests. And difficult to manage.

SlixV

September 12th, 2010

will learn all of this later..by the way.very nice articles

Maxu'

September 12th, 2010

Nice article Max, very good job. Will recommend it to my junior colleague.

Chesterton Spartacus McDoogles III

September 13th, 2010

#11 is iffy, but you did say that it is subjective. Personally, I’ll take reduced HTTP requests any day, but I’m also capable of commenting my stylesheets to make it simple to find particular sections.

#2 however is flat out wrong. An ID is _not_ the most specific method of addressing a particular element. I don’t know about your websites, but mine generally span more than a single page. Certainly, you may be using an unordered list for navigation purposes for one page, but what if you opt for an ordered list for another page and you want different styles applied? For instance, I manage a site where some sub-sections have additional navigation. By using the same ID tag, I can easily apply the same JS flyout controls (with CSS fallbacks for no scripting) but set different styles if I’m using an ordered or unordered list.

Besides that, what if someone else needs to make changes to the site? By marking my primary navigation as ul#navigation, everyone _knows_ that all those styles are expected to be applied to an unordered list and not to a div. Just #navigation semantically means nothing without context.

To be honest, CSS specificity is, in my experience, the biggest mistake developers make when addressing CSS. Simple styles applied to a wide range of elements is a good thing, but by being very specific about your styling means that a later change to the stylesheet doesn’t result in poring over a few thousand HTML pages to ensure you didn’t break something else in the process.

Jennifer R

September 14th, 2010

Great tips, in addition, instead of use Hexadecimal color name like #ffffff you could use #fff…

Adrian Grossett

September 14th, 2010

Fantastic information spot on – I am just beginning to work with CSS I will be bookmarking this page!

Thanks

James

September 14th, 2010

I’ve tried implementing print stylesheets and my experience is that it’s a nightmare (certainly on FF and IE) for all but the simplest pages. Try setting up a table to print, try positioning images, etc. and you’ll have big problems – cross-browser compatibility being among the biggest.

If you’re serious about letting people print anything other than a very simple page, you should rewrite a version of the page specifically for printers and direct your users to that page when they want to print.

Alex

September 14th, 2010

check this css beautifier

http://www.procssor.com/

Robert Kwiecien

September 15th, 2010

Please remember that @import slows down the site performance while the Browser downloads @import stacks sequentiel not parallel!
Use a stack of tags in your HTML head instead. This will perform better if you use a lot of stylsheets.

keif

September 15th, 2010

I’m very much against these types of articles. Too often I read articles that are written for the sake of writing – almost like they’re someone’s homework.

This is not one of those articles. This is very concise, no fluff, no nonsense, and I would argue “this *should* be common sense” but too often have seen the contrary.

Great fuckin’ article.

Hugo

September 16th, 2010

Great article.^_^~

Raymond Selzer

September 17th, 2010

I prefer to split my style sheets as well. But the extra http calls and code added to every page for multiple style sheets always bugged me. So I wrote CSS Combine. It’s a simple little php file, and with a little htaccess magic you can still separate your style sheets to keep your styles separated and easy to maintain AND reduce that other inefficient stuff! PLUS it uses another project on Google Code- CSSmin to minify your css. So not only is your html code only calling one file, but it’s a minified file! Check it out!

http://code.google.com/p/csscombine/

Brian Temecula

September 18th, 2010

@Raymond, nice work on CSS Combine!

Cian Murphy

September 20th, 2010

I’m afraid to admit, I think I regularly do about 6 of those everytime! Thanks for the article.

Craig Pennings

September 24th, 2010

Nice post, I do try to dig into CSS every once in a while and actually do a couple of those things not thinking they are a big deal… just a good reminder to clean up my code. :)

Michael J. Ryan

September 27th, 2010

Regarding a couple of things… First, I’d recommend reading “Event Faster Web Sites” … it’s a really good read…

#2: increased specificity can have the effect of improved rendering timings, when you have similar group sets… identifying the tag for an ID’d selector, you are correct, but nuking the li can slow the rendering/applying of styles within the content on a reflow.

#3, sometimes overriding a single portion of these properties can have unusual effects if you use shorthand… just an fyi on judicious testing.

#8 as an FYI: simply using sans-serif will use Arial on windows, and Helvetica on Mac where each renders better than the other… So, probably better to use sans-serif where you intend the primary font to be Arial or Helvetica. Also, web-fonts are great in this regard. I’m a pretty big fan of sans-droid (in the google web fonts), which is a nice in-between for say Verdana and Helvetica, so it looks good at smaller <= 12pt or so, sizes.

#11 if you're using a server-side framework, you can minify, merge and cache your stylesheets into a single request pretty easily. I often do this for both CSS and JS files… the real gotcha is relative URLs for images in the CSS, when the merged resource URL is in a different directory path from the actual CSS files. Having it as a build/deploy process works as well.

#12 is a must have… I usually do this specifically to nuke most of the styling on the page, outer control margins, adverts, etc… even headers/footers. I'll often have .print and .noprint classes setup for specific print alternatives for elements in the page.

Also, I will do .ns and .pe (no-script and progressive-enhancement) elements, with the .ns/.pe written via document.write in the header from script… this allows for some more graceful alternatives for non-script users (helps for visually impared users, who often disable JS).

Temecula

December 20th, 2010

Thanks for the great write up, particularly the part about shorthand properties. I am now off to find a cheat sheet.

Henrik Kjelsberg

March 18th, 2011

$ sass -t compressed -w ./scss:./css
This little line can improve your life quality folks.
Look into it.

Leave a Comment

Subscribe to the comments on this article.