Media queries enable to write css on the basis of device width, height, orientation(portrait or landscape) and physical attribute.

Everything changes with the time and Internet is no exception. A site which was available only on the web and could be accessed frequently on desktops now has shifted to the mobile phones which may have different resolutions and device sizes due to the boom of smartphones. Even the Internet giant Google recommends responsive sites for better SEO. If your site is not adaptive with those devices, you may be left behind and lose potential users.

What is Responsive Web design

Responsive website design also termed as RWD, in short, are flexible, adaptive and device friendly layouts suitable for almost all screen size and resolution. Days are gone when the mobile-optimized version of the website was in trend for the same purpose.

Now a single site comes with the device friendly layout which response properly with the devices whether it is a desktop, tab or smartphones.

What is viewport

The viewport is simply the visible part of a web page of any device. Generally, it varies device to device. For example, browsers in desktop or large screen have many areas to display the webpage compared to the viewport of tabs or smartphones.

So viewport meta tag enables us to render the webpage as per the device virtual viewport and allows the browser to render the complete page as if it is a desktop browser. If we do not use viewport meta tag the device will render the webpage with default viewport of the device. In this case, if you are browsing a webpage on a mobile with resolution 320px, without viewport meta tag it may show you only those parts of the page which fits in the viewport of your device.

So, we simply put the viewport meta tag in the head of the webpage.

<meta name="viewport" content="width=device-width, initial-scale=1.0", user-scalable=no" />

width=device-width - physical width of the device in pixels.
initial-scale - sets the the initial scaling of the viewport to 1 which simply means that all the content will be set to default device width
minimum-scale - Minimum zoom amount of webpage
maximum-scale - maximum zoom amount of webpage
user-scalable - allow users if the web page can be scaled or not. Possible values - yes / no. Genrally this may not be good idea to set the value no. As user may zoom the page for better readability or viewing experience. If we disable it, user loose the control to zoom the page.

So the standard viewport syntax can be 

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

Mobile first approach

When the Mobile first approach, it becomes a bit easy to customize the site as the screen size grows and also prevents the chance of repeating the extra stylesheet ruleset to be written for larger device-width.

In this approach, the complete site is designed for mobile first then move toward the larger screen.

Smart Phones -> Tab -> Desktop -> For Large screens

Media Queries in CSS3

Media queries allow writing the specific ruleset when the certain conditions are true. For example, if we want to set the background of webpage blue in color of a device with the maximum resolution 320px, we will write

@media screen and (max-width: 320px) {
    body {
        background: blue;
    }
}

This changes the behavior and layout of websites completely. Now Web pages can be customized as per the specific screen resolutions to be adaptive as per the device resolution. 

Media Queries for standard devices

Generally, there are many sites which provide the standard breaking points for the different devices. But we suggest defining your own breaking points to learn and understand the technique properly. We can define the media queries as per our site requirement by resizing the browser to find the best suitable breakpoints.

So, we generally target the smartphone, tab, desktop and large screens.

@media screen and (min-width: 480px) {
    /**/
}
@media screen and (min-width: 768px) {
    /**/
}
@media screen and (min-width: 1024px) {
    /**/
}
@media screen and (min-width: 1400px) {
    /**/
}

Creating a complete responsive webpage with CSS3 Media Queries

Let's proceed to design a simple responsive webpage with media queries. Our page structure is simple and easy. Here is the basic structure.

-Header
     -Navigation
-Content
     -Two Column
-Footer
     -Four Column

We have created navigation, added some content to the page, created the columns and footer with four columns. In the head of the webpage, we have added title and meta with two stylesheets. The first stylesheet - style.css has universal and common style rule set for the site and the second stylesheet named media-queries.css which contains all the media queries and breakpoints for the site.

It is good practice to separate the stylesheet for media queries. It becomes easy to maintain and update in future if any update required.

Here is the HTML Markup -

<html>

<head>
    <title>RWD Tutorial - CodeRomeos</title>
    <!-- Common and base stylesheet -->
    <link href='style.css' type='text/css' rel='stylesheet'>
    <!-- stylesheet for rwd -->
    <link href='media.css' type='text/css' rel='stylesheet'>
</head>

<body>
    <div class='wrapper'>
        <!-- Header -->
        <header>
            <nav>
                <ul>
                    <li><a href='#'>Home</a>
                    </li>
                    <li><a href='#'>About</a>
                    </li>
                    <li><a href='#'>Blog</a>
                    </li>
                    <li><a href='#'>Services</a>
                    </li>
                    <li><a href='#'>Contact</a>
                    </li>
                    <div class='clrfix'></div>
                </ul>
            </nav>
        </header>

        <!-- Main Content -->
        <div class='content'>
            <div class='slide'>
                <img src='images/slide.png'>
            </div>
            <div class='columnLeft'>
                <h2>Dolor sit amet</h2>
                <p>
                    Lorem ipsum dolor sit amet, impedit voluptatibus mei an. Eam in natum nonumes ceteros. An cum dictas probatus, ea tation graeci audire sea. Vel id verear prodesset. An justo facilisi deseruisse ius, cu vel quod corpora. Ex eum sale ludus aliquando. No altera ullamcorper duo.</p>
                <p>
                    Sumo explicari his ut. Eam soluta reprehendunt ut, has liber nostro ex, pro at iudicabit evertitur theophrastus. Ut mei blandit accusata similique, sed erat senserit te, an nam movet feugiat. Dicant convenire gubergren mel ei, nec ut idque decore. Putent persequeris ei sea, cu quo inermis consetetur, ea eum appareat suavitate. Quo ex velit laudem, in has dicam commune. Ius quidam conceptam deterruisset in, tempor officiis ei his. Quis tractatos prodesset est id, te nibh quaestio ocurreret mel. His id sonet impetus iracundia, mea te omnes latine. <a href='#'>read more..</a>
                </p>
                <p>
                    Causae hendrerit ne sea. Qui at persius sapientem. Cu qui ipsum corpora fabellas, doctus detracto praesent ad sit, his vero fugit disputando ei. Te est saperet legimus, mei at integre admodum abhorreant.
                </p>
                <p>
                    Lorem ipsum dolor sit amet, impedit voluptatibus mei an. Eam in natum nonumes ceteros. An cum dictas probatus, ea tation graeci audire sea. Vel id verear prodesset. An justo facilisi deseruisse ius, cu vel quod corpora. Ex eum sale ludus aliquando. No altera ullamcorper duo.
                </p>
                <p>
                    Sumo explicari his ut. Eam soluta reprehendunt ut, has liber nostro ex, pro at iudicabit evertitur theophrastus. Ut mei blandit accusata similique, sed erat senserit te, an nam movet feugiat. Dicant convenire gubergren mel ei, nec ut idque decore. Putent persequeris ei sea, cu quo inermis consetetur, ea eum appareat suavitate. Quo ex velit laudem, in has dicam commune. Ius quidam conceptam deterruisset in, tempor officiis ei his. Quis tractatos prodesset est id, te nibh quaestio ocurreret mel. His id sonet impetus iracundia, mea te omnes latine. <a href='#'>read more..</a>
                </p>
                <p>
                    Sumo explicari his ut. Eam soluta reprehendunt ut, has liber nostro ex, pro at iudicabit evertitur theophrastus. Ut mei blandit accusata similique, sed erat senserit te, an nam movet feugiat. Dicant convenire gubergren mel ei, nec ut idque decore. Putent persequeris ei sea, cu quo inermis consetetur, ea eum appareat suavitate. Quo ex velit laudem, in has dicam commune. Ius quidam conceptam deterruisset in, tempor officiis ei his. Quis tractatos prodesset est id, te nibh quaestio ocurreret mel. His id sonet impetus iracundia, mea te omnes latine.
                </p>
                <p>
                    Causae hendrerit ne sea. Qui at persius sapientem. Cu qui ipsum corpora fabellas, doctus detracto praesent ad sit, his vero fugit disputando ei. Te est saperet legimus, mei at integre admodum abhorreant.
                </p>
            </div>
            <div class='columnRight'>
                <!-- images -->
                <img src='images/image2.png'>
                <p>
                    Causae hendrerit ne sea. Qui at persius sapientem. Cu qui ipsum corpora fabellas, doctus detracto praesent ad sit, his vero fugit disputando ei. Te est saperet legimus, mei at integre admodum abhorreant.
                </p>

                <img src='images/image1.png'>
                <!-- images -->
                <p>
                    Causae hendrerit ne sea. Qui at persius sapientem. Cu qui ipsum corpora fabellas, doctus detracto praesent ad sit, his vero fugit disputando ei. Te est saperet legimus, mei at integre admodum abhorreant.
                </p>
            </div>
            <div class='clrfix'></div>
        </div>

        <!-- footer -->
        <footer>
            <!-- footer column 1-->
            <ul>
                <li class=''><a href=''> hendrerit ne</a>
                </li>
                <li class=''><a href=''> persius</a>
                </li>
                <li class=''><a href=''> disputando</a>
                </li>
                <li class=''><a href=''> abhorreant</a>
                </li>
            </ul>

            <!-- footer column 2-->
            <ul>
                <li class=''><a href=''> hendrerit ne</a>
                </li>
                <li class=''><a href=''> persius</a>
                </li>
                <li class=''><a href=''> disputando</a>
                </li>
                <li class=''><a href=''> abhorreant</a>
                </li>
            </ul>

            <!-- footer column 3-->
            <ul>
                <li class=''><a href=''> hendrerit ne</a>
                </li>
                <li class=''><a href=''> persius</a>
                </li>
                <li class=''><a href=''> disputando</a>
                </li>
                <li class=''><a href=''> abhorreant</a>
                </li>
            </ul>

            <!-- footer column 4-->
            <ul>
                <li class=''><a href=''> hendrerit ne</a>
                </li>
                <li class=''><a href=''> persius</a>
                </li>
                <li class=''><a href=''> disputando</a>
                </li>
                <li class=''><a href=''> abhorreant</a>
                </li>
            </ul>
            <div class='clrfix'></div>

            <p class='copy'>&copy; example.com </p>
        </footer>
    </div>
</body>

</html>

 

Now we will write some CSS for the pages - here is the style.css which have global style -

/* Gloabal */

* {
    margin: 0;
    padding: 0;
    border: 0;
}
li {
    list-style: none
}
a {
    text-decoration: none
}
p {
    margin: 0px 0px 10px 0px
}
.clrfix {
    clear: both
}
body {
    font-family: sans-serif;
    font-size: 15px;
    line-height: 1.5
}
header {
    background: #16acff
}
h2,
p {
    padding: 15px 10px;
}
nav li a {
    color: #fff;
    text-align: center;
    padding: 6px 9px;
    margin-left: 2px;
}
nav {
    max-width: 325px;
    margin: auto;
    padding: 10px;
}
.content,
footer {
    margin: auto;
    max-width: 1170px;
}
.columnLeft {
    padding: 10px 15px;
    box-sizing: border-box;
}
.columnRight {
    text-align: center;
}
footer li {
    border-bottom: 1px solid #aaa;
    width: 85%;
    margin: auto
}
/*Navigation*/

nav li a:hover {
    background: #1266ae;
}
/*Navigation*/

.slide img,
img {
    width: 100%;
    height: auto
}
.content {
    border: 1px solid #ddd;
    border-top: 0;
}
.columnLeft a {
    border-radius: 8px;
    background: #f14911;
    color: #fff;
    font-size: 12px;
    padding: 2px 8px;
}
/*wrapper*/

footer {
    background: #F1F0F0;
    padding: 30px 0px 0px
}
footer .copy {
    font-size: 14px;
    text-align: center
}

 

Now the fun begins. Now we will turn it into a responsive page using media queries. We will be using following breakpoints in our media-queries.css

@media screen and (max-width: 480px) {
    /**/
}
@media (min-width: 481px) and (max-width: 768px) {
    /**/
}
@media (min-width: 769px) {
    /**/
}

 

For our first breakpoint with max-width(480px) - This will take care of the layout for the screens which have maximum width 480px.

@media screen and (max-width: 480px) {
    nav li a {
        float: none;
        display: block;
    }
    .columnRight {
        max-width: 300px;
        margin: auto;
    }
    footer ul {
        max-width: 300px;
        margin: auto;
        float: none;
    }
}

 

In second breakpoint with min-width(481px) and max-width(768px) -  for the screens which comes under the minimum width of 481px and maximum width of 768px.

@media (min-width: 481px) and (max-width: 768px) {
    nav li a {
        float: left;
    }
    .columnLeft,
    .columnRight {
        float: none;
    }
    .columnLeft {
        width: 100%;
    }
    .columnRight {
        max-width: 300px;
        margin: auto;
    }
    footer ul {
        width: 50%;
        float: left;
    }
}

and the last breakpoint with min-width(769px) -  for all the screens which have minimum width of 769px or greater than it.

@media (min-width: 769px) {
    nav li a {
        float: left;
    }
    .columnLeft,
    .columnRight {
        float: left;
    }
    .columnLeft {
        width: 70%;
    }
    .columnRight {
        width: 30%;
    }
    footer ul {
        width: 25%;
        float: left;
    }
}

This is it.

As we can see turning any page to responsive is not a hard job. There can be many breakpoints as many required. But it is good to know and use efficient and standard breakpoints for media queries.

Check out the demo fiddle and resize the page to see the media queries in action.

Edit, change the breakpoints and test it to learn.

Let us know if any issue in the comment box.