Different ways to use media query in css

Media query consists of  a media type and atleast one expression that limits the stylesheet scope by using media features like width, height etc.
With @media query , we can write different css code for different media types. Like, we can write different css code for different media type like for Screen and Printer.
The simplest way to use media queries is to have a block of CSS code in the same stylesheet file. So all the CSS that is specific to mobile phones, would be defined in the following block:
@media only screen and (max-device-width: 480px) {
/* define mobile specific styles come here */
}
But is it difficult to manage code in a single style sheet for several devices. So, we can have different style sheet for specific screen sizes.
<link rel="stylesheet" type="text/css" media="only screen and (max-device-width: 480px)" href="mobile-device.css" />
Another way to add css is @import method -
@import url(480.css) (min-width:480px);
@import url(640.css) (min-width:640px);
@import url(960.css) (min-width:960px);
But it is good to use first two method, avoid @import method (not recommended).
Lets see some media query examples -
<link rel="stylesheet" media="(max-width: 800px)" href="example.css" />
In above example, example.css will be applied when width will be lower than 800px;

@media (max-width: 600px) {
.block {

display: none;

}
}
Above, block wiull be hidden when width will be smaller than 600px.
Change the background color if screen is smaller than 300px in width ;
 
@media screen and (max-width: 300px) {
body {
background-color: lightblue;
}
}

Comments