Browser specific CSS files
December 3rd, 2008
Browsers render HTML and CSS differently. Box model hacking is too messy. And there are just better ways of solving your cross-browser problems.
If the compatibility issues only exist between Internet Explorer and Firefox/Safari the following should suffice:1 2 3 4 5 6 7 8 9 10 |
<!-- Firefox/Safari --> <link rel="stylesheet" href="/assets/css/style.css" type="text/css" media="screen" /> <!--[if IE 6]> <link rel="stylesheet" href="/assets/css/style_ie6.css type="text/css" media="screen" /> <![endif]--> <!--[if IE 7]> <link rel="stylesheet" href="/assets/css/style_ie7.css" type="text/css" media="screen" /> <![endif]--> |
The first and primary style sheet, “style.css,” handles everything presentation-wise. Its processed by every browser. If there are rendering issues between Internet Explorer and Firefox and Safari it should contain values appropriate for Firefox and Safari.
Next we have some inline logic.
<!--[if IE 7]> ...<![endif]--> |
This is viewed as a comment to every browser except Internet Explorer 7. Anything that exists between the opening and closing if statement is processed solely by the Internet Explorer 7 browser.
The next code segment is almost identical to the Internet Explorer 7 block.<!--[if IE 6]> ...<![endif]--> |
JavaScript
A second approach to solving this problem can be a JavaScript solution. In this example I’ll use the Prototype framework.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
document.observe('dom:loaded',function(){ var link = new Element('link',{ rel: 'Stylesheet', rev: 'Stylesheet', media: 'screen' });; if(Prototype.Browser.IE) { if(navigator.appVersion.search(/MSIE\ 7\.0/)>-1) // Internet Explorer 7 link.setAttribute('href', '/blog/examples/2008/12/css/browser-specific-ie7.css'); else if(navigator.appVersion.search(/MSIE\ 6\.0/)>-1) // Internet Explorer 6 link.setAttribute('href', '/blog/examples/2008/12/css/browser-specific-ie6.css'); } else if(Prototype.Browser.WebKit)// Safari link.setAttribute('href', '/blog/examples/2008/12/css/browser-specific-safari.css'); else if(Prototype.Browser.Opera) // Opera link.setAttribute('href', '/blog/examples/2008/12/css/browser-specific-opera.css'); // insert link tag into the head of the document $(document.getElementsByTagName('head')[0]).insert(link); }); |
The code segment has a check being done for each browser. First it checks if the browser is Internet Explorer and then the version. Next it checks against Safari and finally Opera.
The final line of the code segment shows how the link tag is inserted into the document head.
Leave a Reply