Media Queries

We look at websites on a variety of devices. A website viewed on a desktop browser and a mobile can appear completely differently.

For example the screenshot below shows what this website would like on a desktop browser, tablet or phone. You will notice that on the desktop browser that the full navigation bar is visible. When viewed on a tablet browser - as there is slightly less pixels available the navbar will only appear when clicked on, but the appearance is largely still unchanged.

When viewed on a phone, given the size and resolution of the device the layout has been changed from side by side to a stacked layout - as this suits the orientation of the device. This is achieved through the use of a media query.

Phone Browser

Tablet Browser

Full Desktop Browser

This is done by using media queries which define which CSS rules are applied.

If we look at the page below

 This page has the following CSS rules applied:

We want to implement a media query that will change the page to the following layout when the screen size is under 600 pixels.

You will notice that we have replaced the side by side layout with a stacked layout. We have also modified the nav bar.

Media Query Code

We will place the CSS code below in the CSS sheet underneath the existing examples. This will only take affect when the web page is on screen and the width is under 600 pixels.

The CSS rules are only being applied when the media query condition is true 

This means that when the visible window (viewport) is under 600 pixels then the properties within the  { } will be applied to the relevant elements

Alternate Example

Original CSS

New CSS

Media Print

It is possible to use the @media print query to alter the page to be more appropriate to a hard copy. This may involve removing colour backgrounds etc, or changing the orientation of the page etc. This media query would only happen when the the web page is being printed.

Or you may remove headers and footers - for example: