The use of mobile devices to surf the web is growing at an astronomical pace, but unfortunately much of the web isn’t optimized for those mobile devices. Mobile devices are often constrained by display size and require a different approach to how content is laid out on the screen.
A multitude of different screen sizes exist across phones, “phablets,” tablets, desktops, game consoles, TVs, and even wearables. Screen sizes are always changing, so it’s important that your site can adapt to any screen size, today or in the future.
Set the viewport
Pages optimized for a variety of devices must include a meta viewport tag in the head of the document. A meta viewport tag gives the browser instructions on how to control the page’s dimensions and scaling.
- Use the meta viewport tag to control the width and scaling of the browser’s viewport.
- Include width=device-width to match the screen’s width in device-independent pixels.
- Include initial-scale=1 to establish a 1:1 relationship between CSS pixels and device-independent pixels.
- Ensure your page is accessible by not disabling user scaling.
Using the meta viewport value width=device-width instructs the page to match the screen’s width in device-independent pixels. This allows the page to reflow content to match different screen sizes, whether rendered on a small mobile phone or a large desktop monitor.
Ensure an accessible viewport
In addition to setting an initial-scale, you can also set the following attributes on the viewport:
When set, these can disable the user’s ability to zoom the viewport, potentially causing accessibility issues.
Size content to the viewport
On both desktop and mobile devices, users are used to scrolling websites vertically but not horizontally; forcing the user to scroll horizontally or to zoom out in order to see the whole page results in a poor user experience.
- Do not use large fixed width elements.
- Content should not rely on a particular viewport width to render well.
- Use CSS media queries to apply different styling for small and large screens.
When developing a mobile site with a meta viewport tag, it’s easy to accidentally create page content that doesn’t quite fit within the specified viewport. For example, an image that is displayed at a width wider than the viewport can cause the viewport to scroll horizontally. You should adjust this content to fit within the width of the viewport, so that the user does not need to scroll horizontally.
Setting large absolute CSS widths for page elements (such as the example below), cause the div to be too wide for the viewport on a narrower device (for example, a device with a width of 320 CSS pixels, such as an iPhone). Instead, consider using relative width values, such as width: 100%. Similarly, beware of using large absolute positioning values that may cause the element to fall outside the viewport on small screens.