By using this site you agree to the use of cookies.

Learn more

CSS Media Queries

Media queries can be used to control the behavior of a page layout in a variety of window sizes and resolutions.

Edited: 2017-02-08 02:42

CSS Media Queries is a powerful tool used to create responsive website layouts. It can be used to control the behavior of elements in different screen resolutions and window sizes, effectively eliminating the need to design a separate mobile version of a website, and ensuring compatibility with a variety of handheld devices.

Media Queries are supported by most modern browsers.

One of the advantages of using Media Queries, is that you can create a semi-fixed layout, with widths defined in pixels, but still have it adapt depending on available screen space.

The below example will tell the user agent, that the given StyleSheet is to be used if the device has a screen, and if the screen's resolution is between 321 and 768 pixels wide, after which you would have another StyleSheet take over.

<link href="css/tablet.css" rel="stylesheet" type="text/css" media="screen and (min-width: 321px) and (max-width: 768px)">

The below StyleSheet should only be loaded, if your resolution is above 1600px wide.

<link href="css/tablet.css" rel="stylesheet" type="text/css" media="screen and (min-width: 1600px)">

Using media queries inside your StyleSheet

One of the easier ways to use media queries is to create blocks aimed at certain screen resolutions, and keep these blocks in your main CSS StyleSheet. For example, the below blocks will target each their own window size or screen resolution.

  #ColumnA {width:30%;float:right;}
  #MainContent {width:75%;float:left;}
  #MainContent img {max-width: 95%;}

@media screen and (max-width:720px) {
  #ColumnA {width:20%;}
  #MainContent {width:75%;}
}
@media screen and (max-width:400px) {
  #ColumnA {width:95%;float:none;}
  #MainContent {width:95%;float:none;}
  #MainContent img {width:94%;display:block;margin:0 auto;}
}

Imagine a basic float based two column layout. The above will adequately control the behavior of elements in different window sizes. It also applies a max-width to images in the content, preventing them from overflow when there is not enough space for them.

Problems with responsive layouts

In responsive layouts, we face problems with fixed-width elements. Usually these problems are limited to ads and images on our pages.

Images can be handled by applying a max-width in percentages, while ads may require more complicated workarounds.

Some ad networks might offer a responsive ad-unit, which will automatically choose an appropriate sized ad for the space available in the container. Adsense does this, but in their case, the unit is not really truly responsive, and we still have to design around problems with overlapping when the window is resized. See also: Resizing Adsense Units When the Window Resizes