Lesson 9: Responsive Web Design and Media Queries

In this lesson, we will learn about responsive web design, which ensures that your website looks good and functions well on various devices and screen sizes. We’ll focus on media queries, a powerful CSS technique that allows you to apply different styles based on the user’s device characteristics.

Responsive Web Design

Responsive web design aims to create websites that adapt to different devices and screen sizes, providing an optimal user experience. This design approach involves fluid grids, flexible images, and CSS media queries to adjust the layout and styling based on the user’s device.

Media Queries

Media queries are a CSS technique that enables you to apply different styles based on specific conditions, such as screen width or device type. Media queries use the @media rule, followed by a set of conditions and a block of CSS rules that will apply if the conditions are met.

Example:

@media screen and (max-width: 768px) {
  .container {
    width: 100%;
  }
  .sidebar {
    display: none;
  }
}

Viewport

The viewport is the visible area of a web page on a device’s screen. To ensure your responsive design works correctly, set the viewport in the HTML file using the <meta> tag:

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

Mobile-First vs Desktop-First Design

Two common approaches to responsive design are mobile-first and desktop-first:

  • Mobile-first: Start by designing and building for mobile devices, then progressively enhance the design for larger screens using media queries.
  • Desktop-first: Start by designing and building for desktop devices, then use media queries to adapt the design for smaller screens.

Example of mobile-first design:

.container {
  width: 100%;
}

@media screen and (min-width: 768px) {
  .container {
    width: 70%;
  }
}

Actionable Work

  1. Create an HTML file with a simple layout that includes a header, main content area, and footer.
  2. In a separate CSS file, apply styles to create a responsive design that adapts to different screen sizes using media queries.
  3. Include the viewport <meta> tag in your HTML file.
  4. Choose between a mobile-first or desktop-first design approach and adjust your CSS accordingly.
  5. Link your CSS file to your HTML file and preview your work in a web browser, testing the responsiveness by resizing the browser window or using device emulation tools.