Tip: Using a backslash in CSS hacks and workarounds

You may have seen the backslash character ( \ ) used in CSS, often without any explanation as to why it works.

I’ll give you an example, and then I’ll explain when the backslash can be used. In setting a width for a div, you see CSS rules like this:

#somediv {
width: 682px;
w\idth: 680px;
border: 1px;
}

This example uses two width declarations because of IE5.x for Windows’ broken box model. (In Quirks mode, IE6 also uses the broken box model. In Standards mode, IE6 uses the correct box model.) Assume the width you really want for the div is 680px. Adding a 1px border on every side of the div adds two pixels to the width of the div in a browser with a broken box model. A standards-compliant browser includes the 2px border in the 680px specified for the div. As you might have guessed, this use of the backslash to set width is known as the box model hack.

It is important to notice that the declaration (w\idth: 680px;) for compliant browsers follows the declaration for broken-box-model browsers in the Cascade. Here’s what happens. IE.5x reads the width: 682px; declaration but skips over the following w\idth:680px; because it doesn’t understand a property with a backslash. A compliant browser reads the first declaration, but implements the second declaration. The compliant browser implements the second declaration because it does understand a property with a backslash, and because the declaration is later in the Cascade.

Why does the backslash work? It turns out that the backslash is an entirely legal character. In fact, it will not stop your CSS from validating. There is one restriction on its use. You cannot place the backslash before any letter used for the hexadecimal color codes–a,b,c,d,e or f–or unwanted effects will befall you.

3 thoughts on “Tip: Using a backslash in CSS hacks and workarounds

  1. Hi Virginia, Donna here and tried to sign in but got an error so don’t know if this will work either.

    Thanks for the thorough explanation of the box hack. It feels real weird to me that the back flash is legal. Does it matter where you put it in the word?

    best
    Donna

  2. Hey Donna,
    The W3C has listed three times when the backslash (or escape) character can be used at http://www.w3.org/TR/CSS21/syndata.html. None of these uses mentions using backslashes to filter CSS rules for specific browsers, which is why it is technically a hack, even though it validates. As for where it can be in a word, I’ve always seen it before a vowel, but I don’t know if that is required.
    Virginia

  3. Pingback: Quora

Leave a Reply