CSS Media Queries

CSS Media Queries allow us to costomize the presentation of your web pages for a specific range of devices like mobile phones, tablet, desktop, tv etc. without any change in markup.

Media queries can be used to check many things, such as:

  • width and height of the viewport
  • width and height of the device
  • orientation (is the tablet/phone in landscape or portrait mode?)
  • resolution

Media Query Syntax

A media query consists of a media type and can contain one or more expressions, which resolve to either true or false.

@media not|only mediatype and (expressions) {
  CSS-Code;
}

The result of the query is true if the specified media type matches the type of device the document is being displayed on and all expressions in the media query are true. When a media query is true, the corresponding style sheet or style rules are applied, following the normal cascading rules.

Unless you use the not or only operators, the media type is optional and the all type will be implied.

You can also have different stylesheets for different media

<link rel="stylesheet" media="mediatype and|not|only (expressions)" href="print.css">

CSS3 Media Types

ValueDescription
allUsed for all media type devices
printUsed for printers
screenUsed for computer screens, tablets, smart-phones etc.
speechUsed for screenreaders that “reads” the page out loud

Media Queries Simple Examples

One way to use media queries is to have an alternate CSS section right inside your style sheet.

The following example changes the background-color to lightgreen if the viewport is 480 pixels wide or wider (if the viewport is less than 480 pixels, the background-color will be pink)

See the Pen media query 1 by Arpit (@soniarpit) on CodePen.

The following example shows a menu that will float to the left of the page if the viewport is 480 pixels wide or wider (if the viewport is less than 480 pixels, the menu will be on top of the content)

See the Pen media query 2 by Arpit (@soniarpit) on CodePen.

Previous: CSS Flexbox

Next: CSS Wildcard Selectors