By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Controlling the viewport width on handheld devices

How to make media queries work on handheld devices.

Edited: 2015-04-01 11:43

Can you can recognize the following scenario?: You have gone through the extra trouble of creating CSS media queries, which makes your site gracefully degrade, on devices with narrower screen widths – but for some reason it just doesn't work. It works in the browser, on your desktop – perhaps even when using the developers tools – but you just can’t make it work on your fanzy smartphone.

The problem is actually easily solved. But before we get into all the details, lets just try and explain why it doesn't work.

Assumptions on handheld devices

Most handheld devices will apply their own assumptions, when viewing a web page. This seems rather unnecessary – especially when considering the presence of CSS media queries in the stylesheet. Yet, these assumptions are what causes the overruling of your media queries altogether – the device simply assumes, that you are viewing a desktop version of the page. When this assumption takes place, the device will typically adjust its viewport, to allow enough width for the desktop version to be displayed – this is what leads to the zoomed out chaos that we want to avoid.

Stopping this from happening can be done in two ways, either through a CSS @viewport rule, or through a meta tag which is placed in the head section of the HTML of a page. Obviously we would prefer to use the CSS solution, but some older devices only seem to support the meta tag solution. Which one to use for your own site, is entirely up to you.

The viewport meta element

To control this behavior, we can use the viewport meta tag. This tag controls the available width provided for your web page, typically some devices will set this higher than the actual width of the device display, which results in a zoomed-out desktop version of the page.

The best setting for the viewport element, for flexible websites, is likely to just set it at the device-width, and then control everything with your stylesheet.

<meta name="viewport" content="width=device-width">

It might also be necessary, to set the initial scale to 1 for some devices, which will remove any initial zooming applied by the device.

It is also possible to prevent zooming altogether, but this is not recommended. Disabling the ability for users to zoom, can be very annoying to the visitors of a page, and will typically create usability issues for your site – as such, try to avoid disabling of such build-in features.

The CSS solution

The @viewport rule can be used in combination with the viewport meta element, or as a standalone solution. You should just consider possible drawbacks, such as older devices and browsers not supporting it.

The implementation is straight forward, as demonstrated in the below example:

    zoom: 1.0;
    width: device-width;