Only Set The Viewport Width For Mobile Devices

10 years 1 month ago

I know I am going to need this again. This saved me from a decent into madness figuring out why I couldnt get the iPad view to look right. Normally I don't make the iPad view of the site responsive. I just give the user the desktop experience. So setting the viewport to always use "width=device-width" was making the iPad have to scroll to see the 960 pixel width.

The method below will only apply the "width=device-width" to phones where the responsiveness matters and ignore iPads. Credit to Jeff dePascale for posting this clever and clean code.

<meta id="viewport" name="viewport" content="" />

Now, add some simple JS to modify the value to whatever your conditional needs may be:

if (screen.width < 500){
   var vp = document.getElementById('viewport');
   vp.setAttribute('content', 'width=device-width, initial-scale=1');
}

Icons made by Freepik from www.flaticon.com is licensed by CC BY 3.0

< Return to Code Listing