views:

296

answers:

4

I'm trying to use the IE specific conditional statements to alter class settings based on browser type. I was under the impression they could do this but I can't seem to get it working.

Below is a simple example, if the browser is IE the text should be blue, otherwise text should remain red.

"The browser is IE" statement in the body works fine, if I open firefox it's not there, internet explorer.. it is.

What am I doing wrong?

<html>
<head>
<style type="text/css">
.class{color:red;}
<!--[if IE]>
.class{color:blue;}
<![endif]-->
</head>
</style>
<body>
<!--[if IE]>
This browser is IE
<![endif]-->
<p class="class">Color changing text based on browser</p>
</body>
</html>
+1  A: 

Apparently they don't work within the style tag. (see here: http://reference.sitepoint.com/css/conditionalcomments)

It appears you can use them within the head tag, though, and include an external CSS file if it is IE, and hide that css file if it is another browser.

Ken Pespisa
+9  A: 

Firstly your code doesn't work - you should have the css read .color not .class

Second the conditional statements just don't work inside css. So instead write your code such that the conditional is around the IE specific styling.

<html>
<head>  
    <style type="text/css">
        .color{ color:red; }
    </style>

    <!--[if IE]>
    <style type="text/css">
        .color{ color:blue; }
    </style>
    <![endif]-->
</head>

<body>
    <!--[if IE]>
    This browser is IE
    <![endif]-->
    <p class="color">Color changing text based on browser</p>
</body>
</html>
Gavin Miller
Psssh, be nice.. Got my classe's mixed up in my head and didn't double check my work. I like your solution better because I feel that creating an entire style sheet isn't nessacry unless I had a large amount of css to be conditionalized. ;) So I will be giving you the credit, but Ken's is right as well. Thanks for the help LFSR
payling
@payling - didn't know if it was a mistype or if that's how you had actually written it
Gavin Miller
A: 

If the 'hack' is targeted on IE6 or older you can however also do as follows:

.color {
    color: red;
}

* html .color {
    color: blue;
}

Note the "* html" prefix. This is only parsed by IE6 and older. You can also use the "!important" declaration. The particular line would then be ignored by IE6 and older.

.color {
    color: red !important;
    color: blue;
}

If you have relatively a lot of them, a better practice would be to load an additional CSS stylesheet file using the conditional statement.

BalusC
A: 

you can also do color: red;_color:blue;

Mark