Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to make a page responsive

Short answer

Start with a meta tag in head — without it a phone shows the page as a shrunken copy of the desktop one:

<meta name="viewport" content="width=device-width, initial-scale=1">

Three basic rules

Widths use max-width instead of width, images never overflow their parent, and sizes include padding:

<style>
  * { box-sizing: border-box; }
  .container { max-width: 600px; margin: 0 auto; padding: 0 16px; }
  img { max-width: 100%; height: auto; }
</style>
 
<div class="container">
  <h2>Our story</h2>
  <img src="/media/photo-800x500.jpg" alt="">
</div>

The 800px wide image shrinks to the container's width, and the container itself shrinks to the screen width.

A layout for the screen

Next comes the layout: flexible flexbox and grid layouts, and media queries where things need to rearrange. It is handy to build for a phone first and then add columns for wide screens with min-width.

Common mistake

Fixed widths like width: 960px are the main cause of sideways scrolling on a phone. One such table or image breaks the whole page. Look for them when the page "slides" sideways: the device emulation mode in developer tools shows them quickly.

Functions used in this recipe

  • <meta> — Page metadata: encoding, phone settings, a description for search engines.
  • max-width — The maximum width: the element can be narrower, but never wider.
  • @media — Applies rules only under given conditions — the window width, the system theme and others.
  • box-sizing — Whether `width` and `height` include the padding and the border.

Thanks for reading!

Donate to the site — we work hard for you.