If you know CSS, you know that the above just seems to good to be true. Well, it is!
You really can’t make this happen without a little JavaScript. But, with a little JS, we can make our CSS much more complete.
Let’s imagine that we wanted to apply a whole bunch of CSS rules to Mac OS X browsers only. Wouldn’t it be great if we could just do something like:
p { line-height: 1.5em; }
.mac-os p { line-height: 2em; }
Ideally, this would force all Mac OS X browsers to style paragraph tags with a 2em line height.
Well, as I said before, with a little JavaScript, we can actually make this possible. The below example uses jQuery.
if(navigator.userAgent.indexOf('Mac') > 0)
$('body').addClass('mac-os');
Essentially, we’re adding the mac-os class name to your body tag if a Mac OS operating system is detected, which makes the above CSS rules possible!
Quick Tips
- You may not have the jQuery library loaded, in which case, this is easily done with “traditional” JavaScript:
document.getElementsByTagName('body')[0].className += " mac-os";
- If you wish to target only Webkit browsers on the Mac (Safari and Chrome), you can couple this tip with webkit’s proprietary media query as follows:
@media screen and (-webkit-min-device-pixel-ratio:0) { /* this will target only Mac Safari and Chrome browsers */ .mac-os p { line-height: 2em; } }
- Similarly, if you wanted specific styles to target individual Mac browsers, you could do the following:
if(navigator.userAgent.indexOf('Mac') > 0) $('body').addClass('mac-os');
if(navigator.userAgent.indexOf('Safari') > 0) $('body').addClass('safari');
if(navigator.userAgent.indexOf('Chrome') > 0) $('body').addClass('chrome');
Then, within your CSS, you’re able to do something like the following:
.mac-os.safari p { line-height: 2em; } .mac-os.chrome p { line-height: 1.75em; }
- Although these tricks may do the job, they may cause issues for you down the line. It may make sense to “reset” your CSS styles first. Each browser has a different set of defaults styles for each element (some might have a line height of 1em for paragraph tags while others have 1.25 em as the height).The best way to ensure consistency is to first set a base style for all elements. This technique is popular within WordPress themes but can be done easily by adding this one line of CSS to the beginning of your stylesheet:
Minified CSS reset styles