Main Page Content
Assigning Browser Specific Styles
As is well known, most browsers have their own, highly idiosyncratic interpretation of CSS, thereby making the life of us web developers more difficult. In practice, it is especially important to make a distinction between Netscape 4 and all other browsers. This article discusses a simple way of doing just that.Of course you can write a browser detect and then
document.write
the correct <LINK>
tag into the document, but personally I find this solution cumbersome and boorish, especially when we have an excellent alternative. Styles not for Netscape 4
First for the simple part: how to disable a style for Netscape 4. The technique hinges on the fact that Netscape 4 does not support the@import
declaration by which you import a second style sheet. Since Netscape 4 doesn't see the second sheet at all, you can concentrate your dangerous styles (borders, especially) in this sheet.@import url(extra.css)
imports the extra style sheet extra.css into your normal style sheet.Please note that, while Netscape 6 does support @import
it requires the declaration to be the very first in the style sheet. This is a correct (though tedious) implementation of the CSS specs. The advantage is that if you wish, you can restrict certain styles to Explorer by placing the @import
later in the regular style sheet.So far this is easy, now for the harder part.Styles only for Netscape 4
By a judicious use of@import
it is also possible to define style sheets for Netscape 4 only, the exact reverse of what we did before. Let's take a common example: we want our fonts to be exactly matching in Netscape and Explorer. While a 12px font looks perfect in Explorer, it is too small in Netscape 4. We'd rather give this browser a 13px font size.Now if we do this in our normal style sheet:@import url(extra.css)and this in extra.css:p,td,li {
font-size: 13px;}
p,td,li { font-size: 12px;}it doesn't work. Imported styles are less specific than the styles in the regular sheet that imports them. This means that the browsers (except for Netscape 4) read out the 12px font size from the imported style sheet but overrule it in favour of the 13px declaration in the regular style sheet. So your fonts are too large in Explorer.Now we get to the trick. The trick is to give your body tag a class:
<body class="ie">
Change the imported extra.css tobody.ie p,body.ie td,body.ie li { font-size: 12px;}Now it works perfectly! The trick is that the 12px style in the imported style sheet is now more specific than the 13px definition in the regular style sheet. After all, the 12px style gives a rule for elements inside an element with a certain class, while the 13px style only works on elements in general. Thus the 12px style overrules the 13px style, except in Netscape 4 which never sees the 12px style.Simple and efficient, no need for browser detects.