An Introduction to CSS Media Queries

Category:

Tutorial Topic:

Due to the increasing use of mobile devices for web by users now a days, responsive design has become very important for almost every type of website. CSS media queries play a very important role in creating responsive designs and templates.

Media queries basically limit the usage of CSS code to specific screen resolution range. So, you can specify different CSS codes and styles for different types of screens and mobile devices.

Here is a sample media query to limit the enclosed CSS code to screen sizes ranging between 320px and 480px:

@media screen and (min-width:320px) and (max-width:480px) {

}

The following code will Limit the CSS code to all screens having width equal to or less than 960px:

@media screen and (max-width:960px) {

}

The following code will Limit the CSS code to all screens having width equal to or greater than 960px:

@media screen and (min-width: 960px) {

}

Media queries are very helpful in showing and hiding elements according to the screen size. There are usually elements in a web page you want to show for larger devices and hide for smaller devices and the opposite is true as well.

Suppose you want to hide Images with class .desktop for screens of less than 480px width, then:

@media screen and (max-width:479px) {
    .desktop {
        display: none;
    }
}

Similarly, suppose there is a section with ID #section-1, which you don't want to show on devices having widths ranging from 320px to 960px, then:

@media screen and (min-width:320px) and (max-width:960px) {
    #section-1 {
        display: none;
    }
}

It is always recommended to design your website for mobile screens first and then proceed to the larger screen design.