Using Media Queries for Responsive Web Design

You might have used the media attribute while attaching styles to target screen or sometimes to target printer by using ‘screen’ and ‘print ’ media types. Brallie, handheld, projection etc are the media types along with the above two that were supported in CSS2 and HTML4. By using these media types you can target any specific media. CSS3 introduces a new feature to make things responsive called as Media Query. It checks for the certain  attribute  like width, height and color and applies the respective stylesheet. For example-

<link rel=”stylesheet”   media=”screen and (color)”   href=”stylesheet.css” />

The above line means that the styles stylesheet would be applied to the media type of screen and the media must be color screen. Media Query is a logical expression which is either true or false.  If it is true respective stylesheet would be applied. So we can have Media Queries depending on the type of devices we are wishing to target. Consider the following example-

<link rel=”stylesheet”   media=”screen and  (min-width:320px) and (max-width:480px) href=”stylesheet.css” />

The above stylesheet is applied to the document only if the device screen size is 320px or more than that and less than 480px. Note that the use of ‘and’, It is actually working as logical AND. For logical OR we can use comma.  Like color in the first example, we have used min-device-width and max-device-width. These are the features that we use in the Media Query to test about the certain feature of the targeted device based on which the stylesheet is applied. Most of the features accepts ‘min-‘ and ’max-’ prefixes . The complete list of the features is listed below

  1. Width
  2. Height
  3. Device-width
  4. Device-height
  5. Orientation
  6. Aspect ratio
  7. Device-aspect-ratio
  8. Color
  9. Color-index
  10. Monochrome
  11. Resolution
  12. Scan
  13. Grid

I am attaching a demo to get the idea about the power of Media Query to make the things responsive. If you are checking this demo on Google’s Chrome, you can either re-size your browser window or click on the settings button at the bottom right of the developer toolbar. Select the User Agent and device metrics. If you are checking the demo on any smart phone, then let me know your feedback. I am continuing this topic in the next post to explore the above listed features.

About the Author

Pravin Varma

Tech Lead at Calsoft

You may also like these