Conditional stylesheet by useragent

Problem

What is the best way to choose the stylesheet that will be shown depending on the useragent?

Example, i want to show a css style for Android and a different one for IPhone.

  • Is it possible with css only?
  • Can i use something like media queries?

Thanks in advance

Problem courtesy of: HaSuKrOnOs

Solution

With Internet Explorer you can use conditional comments (http://msdn.microsoft.com/en-us/library/ms537512.aspx) to include stylesheets in a specific browser. This technique does not work in other browsers, and I believe it does not work in the latest version of Internet Explorer.

To my knowledge, the only way to accomplish this is with Javascript. The simplest method is to add a class to the HTML tag of the page (i.e. ".android" or ".iphone") with Javascript based on the user agent string. In the CSS simply reference .android or .iphone in your stylesheet to specifically target one or the other.

However, the best approach is to avoid doing specific browser detection whenever possible. Feature detection is the preferred approach (http://www.joezimjs.com/javascript/feature-detection-vs-browser-detection/). This is an exception as your intentions are to have a different theme based on the device.

See the isMobile Javascript library (https://github.com/kaimallea/isMobile) to easily detect an Apple or Android device. As long as the stylesheet isn't huge for each theme, I would recommend merging the Android and Apple stylesheets into one. Than use isMobile library with a little custom Javascript to add the necessary CSS class to the HTML tag.

Solution courtesy of: Jason

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.