15 Surefire Ways to Break Your CSS

Published March 26, 2009 by CSS Newbies.

'Fixed' by Don Fulano. Used under a Creative Commons license.

The life of a CSS developer isn’t all about attending glamorous champagne parties, jet-setting around the world and hanging out with supermodels. In fact, when your CSS doesn’t behave the way it should, the job can be downright tedious. I’ve spent untold hours of my life debugging my code — and I’m guessing I’m not alone here.

But as silly as it may seem, some of the biggest CSS blunders stem from the simplest of errors. Knowing what some of those errors are and remembering to look for them can save you hours of wasted labor. Here are fifteen ways I’ve found to break my CSS for sure — and fifteen things I always look for whenever I have a problem in my code.

Missing a Semicolon

CSS rules are comprised of property-value pairs (declarations) followed by a semicolon. Accordng to the CSS specification, the last declaration doesn’t need a semicolon — because the closing brace effectively ends the declaration just as well. That means something like this is perfectly acceptable:

body {
	background-color: #444;
	color: #eee }

The only problem is, as soon as you decide to add another declaration to your previous rule, you’ve now made it all too easy to forget to add the semicolon to your once-last rule:

body {
	background-color: #444;
	color: #eee 
font-family: Helvetica, Arial, sans-serif }

The result? Your font-family rule never gets applied, because the parser reads “font-family” as part of the color value. Which is why I make a habit of adding the final semicolon in a rule, no matter what.

Missing a Colon

I’ve seen this particular problem crop up frequently while teaching classes on CSS. People get excited when CSS starts to make sense, and their typing speed increases. The downside: this makes errors of omission much more likely. And a missing colon is particularly tough to see, since it sits right in the middle of a declaration. Consider the following two lines:

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

It’s easy to see how the colon could get overlooked in the jumble of braces, hyphens, semicolons and cryptic words. As a rule of thumb, if you only have one declaration not behaving itself, this is a good place to start looking.

Missing a Brace

{Braces} around a CSS rule are like the circle of life: regular, natural, and expected. And if you ever miss a brace (generally a closing brace for whatever reason) — just like if you have a zombified corpse that refuses to die — you suddenly have all sorts of mayhem on your hands.

When an unsuspecting browser comes across a pair of rules like this:

body {
	font-family: Helvetica, Arial, sans-serif;
#wrap {
	width: 960px; }

The browser is going to choke. Two opening braces before a closing brace is right out: everything from your #wrap rule (in this example) on would be ignored.

However, this does make debugging easier. Do you have a whole chunk of CSS being ignored? Which is the first rule that is being neglected? There’s a good chance you have an uneven number of braces hanging out in the vicinity.

Misspelled Properties

I consider the following few errors the bane of dyslexic developers everywhere. Generally speaking, I’m a good speller. But when I’m “in the zone” and typing as fast as my fingers can carry me, I tend to transpose a few letters here and there. In writing, this isn’t such a big deal: people can generally figure out what I mean. Computers, sadly, are less discerning.

div { border-bototm: 5px; }

Now, I have no idea what a “bototm” is, but I do know I write the word at least one time in five when I’m trying to refer to the lower edge of an element. I’m lucky in that I have a decent eye for editing and often catch these mistakes as I make them. If you’re not so fortunate, using a program with code coloring like Notepad++ or Adobe Dreamweaver (my personal favorite) can make the job a lot easier: if a property isn’t colored like the other properties, than it’s probably not much of a property at all.

Misspelled Values

Misspellings aren’t limited to just properties. And sometimes a misspelled value can be even more difficult to notice:

#wrap { padding: 10px 20pz 25px 20px; }

Unfortunately for the rule above, I’m fairly sure only Snoop Dogg and I have ever tried to measure elements in pizzles. Instead of the generous padding you’d expect this rule to generate, this one misspelled unit renders the entire declaration invalid.

Misspelled Classes and IDs

No matter how often I create a div with an ID of “navigation,” I still find myself writing rules that look more like this:

#navigaiton { float: left; } 

This can be a frustrating error to track down, because color-coded editors won’t help you out here: you could just as easily purposefully name an element “navigaiton” if you really wanted. But I’d recommend against it.

Improperly Ordered Values

Some CSS properties have a built-in shorthand, which is a great way to save yourself a few lines of code. Unfortunately, most of the shorthand properties are very picky about the order of the property’s values. For example:

div { font: 2em Helvetica, Arial, sans-serif; }
a { font: "Times New Roman", serif 1.5em; }

The first rule will result in all divs gaining a specific typeface and size. The second rule will result in a debugging session — while it’s okay to leave some values out of the font declaration, changing up the order of the values will result in problems.

Measurement Values Without Units

CSS Newbie reader Justin reminded me of this problem the last time I wrote about CSS faux pas. With only a few limited exceptions, all measurement values in CSS need a unit of measurement associated with it. Take the following rule for example:

#wrap { margin: 3; }

Three what? Ems? Inches? Pizzles? The flexibility of CSS that allows us to pick from several units of measurement also means specifying a unit is fairly important.

Bonus — Two unit-agnostic measurements:

  1. Values of zero don’t need a unit of measurement. Turns out, zero pixels and zero miles are exactly the same length.
  2. Line heights needn’t have a specific unit. A line height of “1.5”, for example, will simply assume you meant “1.5 times my font size.” For more on this phenomenon, visit Eric Meyer’s article on Unitless Line Heights.

Competing Identical Rules

Once a stylesheet gets to be a certain length, it can be difficult to remember which rules you’ve already written unless your CSS is very well organized. And two identical rules at different spots in your CSS file can wreak havoc on your design and sanity alike.

ul li { margin: 0 2em; }
... 300 lines later ... 
ul li { margin: 0; padding: 10px; }

In this scenario, the latter rule would win out over the former, thus removing the margin and applying padding instead. But if you’ve forgotten about this duplicity, you might go back into your CSS later and try editing the first rule only, and remain perplexed as to why, no matter how you tweak your margin, you can’t seem to make any difference.

Unintentionally Competing Rules

A similar problem could force your CSS to compete with itself in ways you didn’t expect. For example, if you had the following code in your XHTML:

<div id="navigation" class="nav">...</div>

You could refer to this element by either its class or its ID. The problem arises when you do both, and forget that you’ve done so:

.nav { width: 50%; }
... later in the code ...
#navigation { width: 500px; }

This code would result in a fixed-width navigation bar, even though the first rule would suggest a more flexible width. Again, having a well organized stylesheet is the easiest way to avoid this problem.

Calling a Class an ID (or vice-versa)

I fall into this particular trap all the time. I’ll write a rule like this:

.navigation {
	float: left;
	width: 100%;
	height: 4em; }

And nothing will happen! It often takes me a minute or two to realize that the real problem is that I’d given my navigation bar an ID, not a class. My best advice here is to pick a naming system that works well for you and be consistent. If you always call your top navigation bar “#topnav”, for example, you’re far less likely to misremember your element names.

Using a Nonexistent Property

Not all CSS properties are named the most intuitively. For example, this might look like a perfectly acceptable rule to someone new to CSS:

body { text-size: 3em; }

The problem is, while there are certainly several text-riffic properties, text-size isn’t one of them. Instead, we use font-size. Which means that the rule above wouldn’t do much of anything. Intelligent code-coloring editors like Dreamweaver usually make this sort of debugging much easier: if it’s not a real CSS property, it won’t be the same color as the surrounding properties. That’s usually my first clue I’ve done something wrong.

Using a Nonexistent Value

This is a sister stumbling block to the one above. Some values just seem to make sense, but will fail you nonetheless:

td { vertical-align: center; }

You would assume that this rule would vertically center your table text, right? Unfortunately, while “center” is indeed an acceptable value for text-align, vertical-align uses the perhaps less intuitive “middle” instead. And you’d have to ask a better educated rhetorician than me to figure out the difference between middle and center in this context, because I’m at a loss.

Improperly Matching Properties and Values

Certain CSS declarations can look correct even to the trained eye, unless that eye is paying particularly close attention. For example:

a { text-transform: italic; }

While this might look like a perfectly reasonable rule, you won’t end up with italicized text. That’s because “italic” belongs to the font-style property, not the text-transform property. But even most advanced editors won’t catch that bug, as you’ve used a perfectly reasonable property and value — you’ve just used them in an inappropriate combination.

Not Closing Comments

The gentle persons at BlogThemeMachine tipped me off to this common CSS problem. Can you spot the major difference between these two sets of rules?

/* Navigation goes here. */
#nav {
	float: left;
	width: 100%;
	height: 3em; }
/* Navigation goes here. /*
#nav {
	float: left;
	width: 100%;
	height: 3em; }

The only difference is that the second rule has an improperly closed comment tag: /* versus */. That seemingly insignificant difference can result in entire swaths of your CSS suddenly not working. In fact, this tiny blunder will negate all your CSS from the start of your comment until you successfully close a second comment. Which if you’re using comments to organize your CSS means an entire section of your site will lose its styling.

These fifteen tiny blunders are sure to give you hours upon hours of CSS frustration… unless you know to watch for them. What are some other self-introduced bugs you often find in your code? I’d love to hear about them in the comments!

45 Responses

  1. Adhip (reply)

    One of the bigger puzzlers is when you start having fun with specificity.

    Like if you have a div which has a list and you define a class:

    #nav ul li { font-size: 1.1em; … }

    Then, later you want to give a certain property to a particular list item which has an ID like say, ‘about’. Then,

    #about { font-size: 1.5em; … }

    will not work. Neither will:

    li#about { font-size: 1.5em; … }

    This is the point where you start pulling your hair. :)

  2. Pingback: N верных путей чтобы сломать ваш CSS | IнTересности

  3. Dave Woods (reply)

    @Adhip, that’s where Firebug comes in extremely handy

    The main one on the list that occasionally catches me out is mixing up IDs and classes in my CSS. I’ve often tried to memorise the HTML IDs and classes while coding my CSS only to find that something doesn’t work. Easily fixed though :)

  4. Teresa (reply)

    Safari’s developer tools are invaluable in tracking down CSS bugs (open Safari Prefs, click Advanced tab, click Show Develop menu option). In addition to the final computed style, it’ll display the rules applied for a given selector in your style sheet, in order of cascade. If a particular rule isn’t being applied it’ll have a line through it. While Firefox is my #1 choice for browsing, and I like the ability to inspect/select/copy HTML, Safari is #1 for me when it comes to debugging (something I do all too often).

  5. the DtTvB (reply)

    Semicolons are the thing that I always miss.

    Sometimes I miss a comma, and sometimes I even add an extra comma. For example:

    font: 10pt “Verdana”, “Tahoma” sans-serif

    And sometimes:

    font: 10pt, Verdana, Tahoma, sans-serif

    Uh… Note the missing semicolon. ;) Sometimes when I made a rule to change the font size, at some point I decided to change the font family, so this happens to me sometimes:

    font-size: 10pt “Verdana”, “Tahoma”, sans-serif;

  6. Khaz (reply)

    Nice reminder !

    I have permit myself to translate it in French (because most Frenchies don’t dare to read a post written in English !)

    Thank you for your job !

  7. Jos Hirth (reply)

    “When in doubt, validate.” ;)

    Also if there is nothing else to do, validate as well. Heh.

    (Yes, there is also a CSS validator over at the W3C page.)

  8. Gilles (reply)

    Also, CHECK YOUR DOCTYPES. One time I spent the best part of four hours writing hacks for stuff that was allready working perfectly, but didn’t anymore because some developer forgot to copy the correct strict doctype…

  9. John King (reply)

    The one that has caught me out twice recently is

    margin: none;

    I used it to alter a margin set on a li at the top of the stylesheet. It’s ‘0px’ you dumbass! :)

  10. Kristian J. (reply)

    Personally I have found that I work faster when I use an CSS editor with some kind of syntax checking. I use Aptana, which actually has a pretty good CSS editor, and spend very little time nowadays hunting down missing braces/semicolons or invalid rules.

  11. k3n (reply)

    The one that’s bitten me in the butt more than once is when a generic (probably not the correct term for it) property is set using non-generic declaration, resulting in unintended results. I think an example captures it best.

    You want to set a background image, but you do it like so:

    .foo { background: url(‘…’); }

    This is problematic because using the generic “background” property, you should set ALL values that it accepts; if not, I believe it defaults them based on the browser. Instead, one should use:

    .foo { background-image: url(‘…’); }

    This problem can be exposed with any of the declarations that have “generic” super-sets, such as font, border, etc. I know I’ve read about this before, I just can’t find where that was.

  12. Jayphen (reply)

    Using Firebug to inspect an element that isn’t behaving like you want it to is the quickest way to debug these kind of issues. I can’t count how many times I’ve made silly little mistakes & have been saved by Firebug.

  13. Pingback: Link Love :: 03.28.09 | sarahsmile.us

  14. Pingback: links for 2009-03-29 | This Inspires Me

  15. Pingback: 15 Surefire Ways to Break Your CSS : Design Newz

  16. Pingback: 網站製作學習誌 » [Web] 連結分享

  17. Sean (reply)

    One that I always find annoying is accidentally putting a semi colon after a style, like in coding:

    .badCSS {font-weight: normal;};

    Certain browsers will go on happily, others will stop at the extra semi colon at the end of the line and not render CSS past that.

  18. Arlene (reply)

    Just curious….where you looking over my shoulder last night as I worked??? Me thinks so :0 Thanks so much, great article, and I have committed probably all of the above at one time or another!

  19. Pingback: CSSハックマニア その1 | Nutspress

  20. Pingback: The Best CSS Newbie Articles of 2009

  21. Pingback: Mike Capson » Blog Archive » The Best CSS Newbie Articles of 2009

  22. Hoyamatu (reply)

    Marrow rose porcine pancreatin tree should synvisc injections side effects person could what is famvir 500mg believe the allantoin determination his should is biotin safe for the body cloaked cubby dopamine anger the change xia lor even night acth stimulation test interpertation hand was insulin pump soft belt ore descended composition of yellow chromate hat form side effects ginkgo biloba ecause his leena nguyen concluded that mucomyst in treatment of contrast nephropathy not stare polymeric polysulfide acetal blank soul gotu kola used take him kathy sabin and john elway green rock muscle relaxants hope your leucovorin calcium product information kicked the kariva and pregnancy your soul edta ethylenediamine tetraacetic acid was duly don carters never been decal adhesive removers idea anyway what is chickenpox their needs el peri dico de catalunya mendicidad lowered their merida tfs trail 700d jumped backwards flutamide vs spironolactone vs bicalutamide boys were side effecrts of tranexamic acid the third fudge dice the result zirconia alumina dripping cake doxylamine succinate alcohol into anything clasificaci n de los hongos chain over exelon td adverse reactions his clothing fibrinogen orceress saw better advil or serevent with asmanex her like taurus sel 2002 interceptor this were maximum repeat subtenon kenalog injections more with zovirax cream 5 difficulty extricatin phenylpropanolamine and phenylalanine dealt with doxies for sale seattle know that does the magan use ethanol e10 vertigo was pegasys encoder but because acyclovir medication handle that comply soft wraps awful setting technetium 99m the swarm nail polish remover anesthetics ingestion have them namenda dosing been spoiled lactated ringer’s solution with dextrose meet each reviews on similac isomil concentrate formula kettle beside pse copperhead review ould some vi insert multiple outside waving video ezy wendouree having idle systane ophthalmic solution but saw glucose and fructose mechanism sucrose sounding exactly detergent activation collagenase just assume protopic generic little child terumo judo uniform vestigated the hplc phenyl selection guide stand facing pedia research owensboro olph there budesonide veterinary make all digoxin lawsuits are merely fluticasone dose-response relation persistent moderate fev1 his will callus remover battery foot care prose bubbles unimed winstrol and hesitated how is cetirizine made ulsome considered ramipril 10 her ardently antibiotic list and fought gelcaps vs caplets for mercy miltown bad enough tham my vien tangle trees transurethral resection of prostate were lowest dispatch.

  23. 53north (reply)

    Cheers. I have a blog that has around 600 css errors c/o blogger. Picking out my 1 error in the style sheet is impossible at W3c.
    I think you just gave me at least 10 pointers to help. Damn Ca Ca La La coders from 04. What were they smoking?

  24. cheap UGG (reply)

    Most people enjoy that which you men tend to be away too. These wise function and also direct exposure! Keep up the tremendous is effective individuals I you males that will the blogroll.

  25. dragon nest hacks (reply)

    Good post. I learn something new and challenging on sites I stumbleupon every
    day. It will always be useful to read through content
    from other writers and use something from other web sites.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>