Media queries

Media queries let you apply different styles to an element based on device size, orientation, type, and pixel density. The media query is, in essence, an if statement about the browser/device properties: if the statement evaluates to true, the styles inside will be applied:

@media screen and (min-width: 600px) {
  // styles to apply
}

The viewport meta tag

Before media queries can be used, the browser needs to know how to control the page dimensions and scaling. The tag's content may contain a number of properties, but using most of them is not recommended. Here's the standard version for a responsive page:

<meta name="viewport" content="width=device-width,initial-scale=1">

Media type

@media print { ... }

Describes a general category of the device that displays the page:

  • all - the default value, applies to all devices
  • screen - applies to devices that display the page on a screen (computers! phones!)
  • print - used when printing and in print preview
  • speech - intended for speech synthesizers.

Dimensions

@media (min-width: 640px) { ... }

Describe the size of the browser window: width, height. Can be modified with min- and max- prefixes (min-width, min-height, max-width, max-height)

Orientation and aspect ratio

@media (orientation: landscape) { ... }
@media (orientation: portrait) { ... }
@media (aspect-ratio: 16/9) { ... }
  • orientation: landscape: the device is wider than it's tall
  • orientation: portrait: the device is taller than it's wide
  • aspect-ratio: width/height: ratio of device width to it's height. Can be prefixed with min- and max-.

Tasks

See the Pen by maciej-kucharski (@maciej-kucharski) on CodePen.

Read more

results matching ""

    No results matching ""