Different ways to use css3 media query in css

A media query consists of a media type and at least 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 types like for Screen and Printer.

The simplest way to use css3 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 a 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 the first two methods, avoid @import method (not recommended).

Let’s see some media query examples –

<link rel="stylesheet" media="(max-width: 800px)" href="example.css" />

CSS & CSS3 Media Query tutorial

In the above example, example.css will be applied when width will be lower than 800px;

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

display: none;

}
}

Above, the block will be hidden when width will be smaller than 600px.

Change the background colour if the screen is smaller than 300px in width ;

 
@media screen and (max-width: 300px) {
body {
background-color: lightblue;
}
}

Leave a Reply