Skip to main content

CSS Media Queries

By SamK
0
0 recommends
Topic(s)

Due to the increasing use of mobile devices 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.

The CSS media queries allow us to define different styles for different media types. Using media queries you can restrict the CSS styles according to many things, such as:

  • size (width and height) of the viewport
  • resolution of the screen
  • orientation (landscape or portrait) of the viewport

There are three types of media:

  • all - Used for all media type devices
  • print - Used for print preview mode
  • screen - Used for screens like computer, tablets, smart-phones etc.

Some common media features are:

  • orientation - Landscape or portrait
  • min-width - Minimum width of the viewport
  • max-width - Maximum width of the viewport
  • width - Width of the viewport
  • min-height - Minimum height of the viewport
  • max-height - Maximum height of the viewport
  • height - Height of the viewport

We 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 of less than 480px:

@media screen (max-width:480px) {
  div {
    background-color: red;
  }
}

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) {
  div {
    background-color: red;
  }
}

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) {
  div {
    background-color: red;
  }
}

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;
    }
}

You can also link to different CSS files for different media and viewport sizes:

<link rel="stylesheet" media="print" href="print.css">
<link rel="stylesheet" media="screen" href="screen.css">
<link rel="stylesheet" media="screen and (max-width: 480px)" href="mobile.css">
<link rel="stylesheet" media="screen and (min-width: 481px) and (max-width: 960px)" href="tablet.css">
<link rel="stylesheet" media="screen and (min-width: 961px)" href="desktop.css">

Please watch the video above for live examples.

Questions & Answers