CSS3: From Knowledgable to Ninja – Part 4 Media Queries

If you’ve ever used a print stylesheet you’ll be familiar with the idea of creating a separate stylesheet to come into play under certain conditions. in CSS2 there were media types, which lets you specify a type of media to target.

<link rel='stylesheet' type='text/css' media='screen' href='css/styles.css' />
<link rel='stylesheet' type='text/css' media='print' href='css/print.css' />
 
@media screen {
  p {font-family:sans-serif;}
}
@media print {
  p {font-family:serif;}
}

CSS3 Media Queries

In CSS3 they extend the idea but instead of targeting a media type they target the capability of the device. Such things it can target are:

  • width and height (of the browser window)
  • device width and height
  • orientation – for example is a phone in landscape or portrait mode?
  • resolution

creating and linking to a separate stylesheet

@media screen and (max-device-width:480px) {
  #wrapContent {width:400px;}
}

This style targets screen devices that have a max width of 480px (i.e. iPhones) to make #wrapContent 400px wide. for this to work we would need to place this at the end of our stylesheet so it will overwrite any styles we’ve set up for the browser.

If you’re going to have a lot more styles and want to use a separate stylesheet you can use the following.

<link rel='stylesheet' type='text/css' media='only screen and (max-width: 480px)' href='smartphone.css' />