HTML Responsive Design

Visitors open websites on phones, tablets, laptops and big monitors. A responsive page changes its layout to fit the screen. HTML and CSS together make it possible, and it needs only a few basic things.


1. The viewport meta tag

Without this line, phones show a tiny zoomed-out copy of the desktop page. Add it in the head of every page.

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

It tells the phone to use its real screen width, and to start with no zoom.


2. Flexible images

<img src="photo.jpg" alt="A mountain" style="max-width: 100%; height: auto;">

max-width: 100% means the image can be smaller than its real size, but never wider than its box.


3. Relative units and flexible widths

  • Use percentages (%), rem and em for widths and font sizes, instead of fixed px.
  • Use max-width to stop a box from becoming too wide on big screens.

4. Media queries

A media query applies CSS rules only when a condition is true, like the screen is smaller than 600 pixels.

<style>
  .box { width: 50%; float: left; }

  @media (max-width: 600px) {
    .box { width: 100%; float: none; }
  }
</style>

On wide screens two boxes sit side by side. On screens up to 600 pixels the boxes become full width and stack on top of each other.


Mobile first

Many developers write the CSS for the small screen first, and then add @media (min-width: ...) rules for bigger screens. It keeps the code simple and works well on phones.

Note: Test your page by resizing the browser window, or open the browser developer tools (F12) and switch to the device mode.

Summary

  • Add the viewport meta tag.
  • Make images flexible with max-width: 100%.
  • Use relative units and media queries.
  • Next: HTML5 Introduction.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write an HTML program to create a navigation menu
Write an HTML program to create a page layout with semantic elements
Interview Questions & Answers
What are semantic elements in HTML5? Give examples
What is the difference between div and section in HTML?
How do you make a web page responsive using HTML and CSS?
What is web accessibility and how does HTML help with it?