Skip to content

January 5, 2013

How to fit your website for the iPad, iPhone or Android

iphone

Mobile devices and their browsers have powerful abilities. And the number one ability of mobile browser, for a front end developers, is a possibility to resize any website for the screen with any resolution.

If you want to fit your website for the iPad, iPhone or Android and make it well, you have to choose and set correct scale factor  which tells how exactly your site will look on a screen of  a mobile device after loading. So, how to do that?

I have found two ways how to detect type of mobile device:

  • Detecting mobile device while checking  user agent name;
  • Detecting mobile device by checking screen resolution of a device using features of “media queries”.

iphone ipad

After detection of the type of  mobile device or its screen resolution, we can set parameter “viewport”, which tells to mobile browser how to make initial scale of your website.

When you use detection of mobile device while checking user agent name (iPhone, iPad, Android), you can use pure JavaScript, without any libraries such as jQuery or other. Code will look like this:

<!-- in head -->
<meta id="viewport" name='viewport'/>
<script>
    (function(doc) {
        var viewport = document.getElementById('viewport');
        if ( navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)) {
            doc.getElementById("viewport").setAttribute("content", "initial-scale=0.3");
        } else if ( navigator.userAgent.match(/iPad/i) ) {
            doc.getElementById("viewport").setAttribute("content", "initial-scale=0.7");
        }
    }(document));
</script>

This source code was taken from the stackoverflow.

If you choose to use a power of “media queries” techniques, you should use some library like Modernizr, and an example of code you can see below:

<meta name="viewport" id="viewport" />
<script src="modernizr.js"></script>
<script>
if(Modernizr.mq("only screen and (max-device-width: 480px)")) 
   document.getElementById("viewport").setAttribute("content","width=650");
</script>

Instead of setting “width=650” you can set “initial-scale” like it was done in previous example. By setting correct number of initial scale you can fit your website for any version of  iPad, iPhone or Android, and for other mobile devices, too.