Responsive Web Design

What is Responsive Web Design?

Responsive Web Design is the process of making your website look and work on any device such as phones, tablets, or desktops. Instead of making separate code for each size you are able to make one version that changes the layout and adjusts screen size automatically using CSS.

Example 1: Media Queries

Media Queries allow you to apply different styles based on the screen width detected. They’re how your site is able to know when to switch layouts from mobile to tablet or desktop.

    
    /* Mobile-first */
    .container {
      padding: 10px;
    }
    
    /* Desktop layout */
    @media (min-width: 1024px) { /* Detects min width */
      .container {
        padding: 30px;
    }
    

Example 2: Flexible Images

A problem with non-responsive websites is that the images don’t shrink properly on small screens. If you have a fixed width for an image then it could overflow from the container or break your layout. Using flexible images you can make the images scale with the screen size by applying CSS.


        img {
            max-width: 100%;
            height: auto;
          }          
    

Max-width: 100% makes it so the image is never wider than the element it is inside. While height: auto makes sure the image doesn’t get stretched or squished.

Example 3: Flexbox

Flexbox is a layout tool in CSS that lets you create responsive and flexible layouts. If you had two containers and on mobile you want them to stack but on desktop you wanted them side by side you could use flexbox.

This is what it could look like.


        .container {
            display: flex;
            flex-direction: column;
          }
          
          @media (min-width: 1024px) {
            .container {
              flex-direction: row;
              justify-content: space-between;
            }
          }                
    

Display: flex turns the container into a flexbox. Flex-direction: column stacks them vertically. If the screen width is 1024px or bigger then it switches to row to make them side-by-side. Justify-content: space-between adds a space between them when they are side-by-side.

Example 4: Viewport Meta Tag

Before any of your responsive CSS can work you need to add the viewport meta tag to your HTML . Without this mobile browsers will zoom out and display your site like it is on desktop.


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

Example 5: Lazy Loading Images

Lazy loading makes it so images and other content that you apply it to will only load when they are needed. For example when a user scrolls down the image will load right before it comes into frame.


        <img src="photo.jpg" loading="lazy" alt="An example image">
    

Best Practices