Parand
Parand

Reputation: 106360

Retrofit existing web page with mobile CSS

What's a good way to add mobile-specific CSS to an existing web page?

The requirements are:

I'm looking at HTML5Mobile boilerplate and various other solutions for the long term, but for the short term I'm looking for a low effort CSS based solution.

I'm hoping for a client-side only solution (as opposed to serving a different page).

Recommendations? Is there a library / article / code snippet that'll help me out?

Upvotes: 4

Views: 571

Answers (2)

ceejayoz
ceejayoz

Reputation: 180105

The best way to handle this is CSS media queries, which let you serve different stylesheets to different browser resolutions and capabilities. One of the major benefits is that you don't have to do browser sniffing or any server-side code, which is a nightmare to maintain when dozens of new devices come on the market each month.

Whereas browser sniffing would require you to add specific detection code to your script for each type or grouping of device, media queries handle even devices you've never heard of.

As a contrived example, this would make your page have hot pink text on mobile browsers and small screens:

@media handheld and (max-width: 480px), screen and (max-device-width: 480px), screen and (max-width: 600px)  {
    body {
        color: hotpink;
    }
}

Lots of good examples of media queries in use:
http://responsivewebdesigns.tumblr.com/

Upvotes: 7

Daniel
Daniel

Reputation: 31579

The best way to do this is use php to return a different css for different browsers.
example:

<?php
header("Content-type: text/css");
$browser = get_browser();
if($browser['platform'] == 'iPhone')
    readfile("iPhone.css");
else
    readfile("normal.css");

Edit:
You can do this on client side as well. to detect the client in javascript you can use

if(navigator.userAgent.match(/iPhone/i))

or something similar for other platforms. To include the specific css you need jQuery Include Many plugin and then use:

$.include('somecss.css');

All together:

<script>
    if(navigator.userAgent.match(/iPhone/i))
        $.include('iPhone.css');
    else
        $.include('Other.css');
</script>

Upvotes: -3

Related Questions