Grom S
Grom S

Reputation: 239

How to target Mac with CSS or Javascript

I need to use specific styles for Mac in my stylesheet. What is the best way to do it?

Upvotes: 6

Views: 4195

Answers (4)

Yannis Dran
Yannis Dran

Reputation: 1529

Only for mac:

 <script>(function(e,t){function n(n,r){if(t.indexOf(n)!==-1)e.push(r)}n("Mac","os-mac");if(document.documentElement){document.documentElement.className+=e.join(" ")}})([""],String(navigator&&navigator.appVersion))</script>

It works like johnhunter's solution, only that it is minified.

Upvotes: 1

johnhunter
johnhunter

Reputation: 1836

In an ideal world you shouldn't need to fork styles for different os. However sometimes a specific design will require it - particularly with styling form elements.

If you really have to, the following script will set a class on the html element:

(function (flags, app) {
    os('Win', 'os-win');
    os('Mac', 'os-mac');

    if (document.documentElement) {
        document.documentElement.className += flags.join(' ');
    }

    function os (s, f) { if (app.indexOf(s) !== -1) flags.push(f); }

}([''], String(navigator && navigator.appVersion)));

You can execute this in the html head which means the page doesn't re-render after the initial loading.

You can then use mac specific css rules like so:

.os-mac #my-element { ... }

Note: The best thing to do is find a solution that doesn't require forking for the OS.

Upvotes: 7

Jacob Oscarson
Jacob Oscarson

Reputation: 6393

The navigator.platform property returns 'MacIntel' on OS X Safari, Chrome and Firefox (I don't have any PPC boxes at hand). If I would do it, I would check for that, and probably put in a class named .mac on the <BODY> tag and use that as a basis for the Mac-specific stuff.

Upvotes: 1

Delan Azabani
Delan Azabani

Reputation: 81384

or JavaScript

if (navigator.userAgent.match(/Macintosh/))
    // do stuff for Macs here, such as load a stylesheet

But really, this is bad practice and you shouldn't do it.

Upvotes: 4

Related Questions