Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 796
Grom S Avatar asked Feb 28 '11 08:02

Grom S


4 Answers

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.

like image 109
johnhunter Avatar answered Nov 14 '22 21:11

johnhunter


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.

like image 32
Delan Azabani Avatar answered Nov 14 '22 23:11

Delan Azabani


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.

like image 29
Jacob Oscarson Avatar answered Nov 14 '22 21:11

Jacob Oscarson


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.

like image 35
Yannis Dran Avatar answered Nov 14 '22 21:11

Yannis Dran