cookiecrook²

Skip to content

Avoiding CSS comment hacks

Although valid CSS comment hacks are invaluable, I'm pretty sure everyone agrees that it's better to avoid them if you can (for future compatibility of new implementations). I wanted to share some techniques that help me avoid overuse of hacks.

  1. Use margin on child elements instead of padding on parent elements. The differences in the box model are well-documented, and mostly revolve around padding and border-width, right? (WinIE pushes those inward, while spec-compliant browsers push them outward.) While you could use hacks to define and redefine those values, why not just use another method to get the same effect without a hack? Specify the width of your containing element with no padding, then add margins to the known child elements of this container.

    div.main {
      width:70%;
      padding:0;
      }
    .main p, .main h1, .main h2, .main h3 {
      margin:0.5em 1em 1.5em 1em;
      }

  2. Let font-size inherit from the body element. Scalable font sizes are the other bane to WinIE5's CSS implementation. I haven't figured out a way to get around the hack completely, but you can implement one hack for the body element and let that inherit all the way down. For example, let's implement our hacks to set the body at a keyword size (WinIE?5 is one step larger than the other browsers, so we'll set it small there, and medium on everything else).

    body {
      font-size:small;
      voice-family:"\"}\"",inherit;
      font-size:medium;
      }

    Feel free to correct if I've left something out (Opera perhaps?), but the idea remains the same. Now all elements will inherit the same size (almost) and the text will remain scalable. Any child element of that root can now take modify it's default size with a unit like Ems or percentages (%) without having to hack it back and forth again for each browser.

    p { font-size:0.8em; }
    td, th { font-size:0.7em; }
    h1 { font-size:200%; }
    h2 { font-size:170%; }
    h3 { font-size:140%; }
    h4 { font-size:120%; }

    Be careful though, when setting the size of elements within elements. A size of small inside small is still small, but 50% inside 50% is 25%. In the above example, if you had a p(0.8em) within a td(0.7em), the font-size would end up being 0.56em (probably not what you intended). This example assumes you would always be using td for tabular data, not layout, however, if you did need a paragraph inside a table cell, you could reset it via the cascade.

    td p { font-size:1em; }

Does anyone else employ similar techniques to avoid hacks? If so, I would love to hear them.


This was originally posted to the CSS Discussion email list and I have also posted it to the companion Wiki. It is possible that a more recent version can be found there. Avoiding Hacks page on the CSS-D Wiki.

Photo by James Craig.