The use of CSS Hacks

Posted: March 21st, 2009 | Author: | Filed under: CSS | Tags: , , , | Comments Off on The use of CSS Hacks

As you all know there are a couple of differences in rendering your website in different browsers (Internet Explorer 6/ 7 / 8, FireFox 2 / 3, Opera and Safari).

You as front-end developer have the responsibility to make sure your webpages are supported for all browsers. Microsoft introduced “conditional commenting” as a sollution, but often you do not want to add in a whole CSS file to fix a single pixel. In these cases you need a “hack” in CSS to accomplish this.

Before I give the solution to your rendering differences in Internet Explorer, you need to understand these hacks should only be used when all other options are eliminated since they are mentioned as final solutions for tiny bugs.

If you want to reach Internet Explorer 7 and below use:

div#example{
    width: 230px; /* For all browsers */
    *width: 234px; /* Only for Internet Explorer < 7 */
}

Note: the ” * ” is not valid according the w3c validation.

If you want to reach Internet Explorer 6 use:

div#example{
    width: 230px; /* For all browsers */
    _width: 234px; /* Only for Internet Explorer 6 */
}

Note: the ” _ ” is valid according the w3c validation.

In some rare cases FireFox and IE6 acts the same but IE7 needs some changes, then use:

div#example{
    width: 230px; /* For all browsers */
    *width: 234px; /* Only for Internet Explorer < 7 */
    _width: 230px; /* Only for Internet Explorer 6 */
}

>>UPDATE (1 september, 2009)<<
IE8 needs a new approach, although this browser becomes more and more to standards, there are still some cases to target IE8 only:

div#example{
     width: 230px; /* For all browsers */
     width /*\**/: 233px\9; /* Only for Internet Explorer < 8 */
     *width: 234px; /* Only for Internet Explorer < 7 */
     _width: 230px; /* Only for Internet Explorer 6 */
}

As IE6 is by far the most buggy of them all, you might need a whole block of IE6 specific CSS, then use the “* html” hack:

* html div#example{
    width: 230px; /* Only for IE6 */
}

Last but not least is a very dirty hack for Safari:

@media screen and (-webkit-min-device-pixel-ratio:0){
    div#example{
        width: 239px; /* Only for Safari */
    }
}

Note: This hack should be used for example for font-weight since this is rendered bolder then in other browsers in all other cases Safari renders the same as FireFox.

Noticed there is no hack for Firefox? If you website looks correct in IE, but not in FF, making chances in your CSS is wrong. Try to get it right in FF first, then fix things for IE.


Comments are closed.