Thursday, November 30, 2006

CSS hack to differentiate between IE 6 and 7

I discovered this quite by accident, and thought this might be helpful for those who find they need to set up different stylesheet rules for formatting in Internet Explorer 6 and IE 7. The crux of this solution is the CSS attribute selector (dentoned as square brackets [] in CSS). It turns out that IE6 does not understand attribute selectors, and, in fact, will ignore the entire associated rule (including rules with more than one selector).


To leverage this difference, two rules can be defined. A normal rule that will be rendered in IE6, and a duplicate rule containing an attribute selector that will be rendered in IE7. In the example below, I use the IE-specific "if" statement to show how you can further differentiate between IE and "other browsers." The solution below was tested in the Windows environment using IE6, IE7, Oprah 9, and Firefox 2.


If you use a different browser or environment, try the code out and let me know what you see.



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>CSS hack to differentiate between IE 6 and 7</title>
    <meta name="author" content="John A. Marsh" />
    <meta name="copyright" content="&copy; 2006 ThreeLeaf.com" />
    <style type="text/css">
        P {
            background:green;
        }
    </style>
    <!--[if IE]>
        <style type="text/css">
            P {
                background:red;
            }
            P[],P {
                background:blue;
            }
        </style>
    <![endif]-->
</head>
<body>
    <p>Blue in IE 6, Red in IE 7, Green in non-IE browsers.</p>
</body>
</html>

No comments: