Here we’re going to have a look at a few CSS browser hacks which you can use in those horrible situations where the page looks perfect in all browsers apart for one (IE6 cough!).
- @import
- <!–[if IE]>
- IE 6 Only Hack
- IE 7 Only Hack
- Firefox Only Hack
- Breaking CSS validation
- To Hack or not to Hack?…
@import
@import is used to link an external stylesheet from within a stylesheet/CSS. Earlier version 4 browsers (e.g. Netscape Navigator 4) do not understand this rule and therefore ignore it.
Use the @import if you need to hide styles from older version 4 browsers:
@import "mystyle.css"; /* hidden from most version 4 browsers */ @import url('mystyle.css'); /* understood by IE4 but not NN4 */
<!–[if IE]> Conditional Statements
Internet Explorer (aka IE) have conditional statements that allow you to give instructions based on the IE and the version of Internet Explorer running.
<!--[if IE]> This will echo if the browser is Internet Explorer <![endif]--> <!--[if IE 5.5]> This will echo if the browser is Internet Explorer version 5.5 <![endif]--> <!--[if IE 6]> This will echo if the browser is Internet Explorer version 6 <![endif]-->
IE 6 Only Hack
If everything works in Firefox, IE7 but not in Internet Explorer 6, use the star html hack:
* html .myclass{ /* this will only work in IE6 */ }
You can also use the underscore hack but I prefer not to as this will cause validation errors in your CSS. Just for reference, here’s an example of the underscore hack:
p{ margin:0; _margin-left:5px; /* only IE6 will process this line */ }
Firefox Only Hack
I came up with this when messing around with child selectors. I don’t know whether it has a name or if other people are using it but it seems to work quite nicely in the version of firefox I was running… (I haven’t tried it in other browsers but it validates fine)
Update: its called the child hack. Opera and Safari should process this aswell.
p.myStyle{ color:red; } p > .myStyle{ color:blue; /* Only Firefox runs this style */ }
Everything but IE6
Heres a hack that works in Firefox and IE7. Handy if you want everything but IE6 to run it. Better still, it validates as well.
html[xmlns] .myStyle{ /* Firefox and IE7 process this but the document must be XHTML to work */ }
To Hack or not to Hack?…
A lot of the time CSS hacks are just a quick solution for us developers, we don’t care how it works as long as it does. However, my advice is avoid this and try to find out why there is a problem in the first place.
A little time spent looking into the problem itself and not a workaround will not only give you a far better understanding of CSS and browser iregularities but also stop you repeating the same thing the next time round.
Tutorial Name: CSS Hacks
Have to learn the basics first 😀 Great article tho