Design Lunatic

CSS3 Media Queries

CSS3 media queries are extremely useful for adaptive layouts. Depending on the visitor’s screen size, aspect ratio, and many other things, you can serve different layouts. For example, if I wanted to target browser viewport sizes that are between 400px and 700px, I could write this in my stylesheet.

@media screen and (min-width: 400px) and (max-width: 700px) {
Adaptive CSS goes here

You will probably use the “min-width” and “max-width” properties most.

Notice I said “@media screen”. This is interchangeable; I could also write “print” for printer layouts, “handheld” for mobile devices such as Androids or iPhones. I could also just write “all” to target all types of devices.

Speaking of mobile devices, I could also target different orientations.

@media handheld and (orientation:portrait) { … }
@media handheld and (orientation:landscape) { … }

Self-explanatory? I hope so.
Orientation-based stylesheets are great because you can squeeze more content horizontally on landscape-oriented devices.

There are other properties, such as “aspect-ratio”, the ratio of the width of the browser viewport to the height. Useful for shrinking elements the right way depending on the ratio. Values are given in “dpi”, dots per inch. Alternatively, you could use “dpcm”, which is dots per centimeter. It supports the “min” and “max” prefixes.

@media print and (min-resolution: 300dpi) { … }
@media print and (min-resolution: 260dpcm) { … }

The “device-height” property is the height of the whole screen, not just the viewport. Of course, there is also a “device-width” property. “Device-aspect-ratio” is the ratio of the screen’s height to the screen’s width.

@media handheld and (device-height: 480px) { … }
@media handheld and (device-height: 320px) { … }

Now, all of these different media queries are written in your stylesheet. However, what if you wanted to serve different stylesheets depending on the media queries? For example:

<link rel="stylesheet" media="print and (min-width: 25cm)" href="whatever.css" />
  • Mobik

    Thanks for helpful and simple tutorial