CSS Media query

CSS Media query

ยท

2 min read

Media query is a CSS technique introduced in CSS3.

It uses the @media rule to include a block of CSS properties only if a certain condition is true.

Adding a Breakpoint

We can add a breakpoint where certain parts of the design will behave differently on each side of the breakpoint.

Desktop view:

Mobile view:

example

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
  background-color: lightgreen;
}

@media only screen and (max-width: 600px) {
  body {
    background-color: lightblue;
  }
}
</style>
</head>
<body>

<p>When the width of this document is 600 pixels or less, the background-color is "lightblue", otherwise it is "lightgreen".</p>

</body>
</html>

You can add as many breakpoints as you like.

I will also insert a breakpoint between tablets and mobile phones.

We do this by adding one more media query (at 600px), and a set of new classes for devices larger than 600px (but smaller than 768px)

Typical Device Breakpoints

There are tons of screens and devices with different heights and widths, so it is hard to create an exact breakpoint for each device. To keep things simple you could target five groups:

Example

/* Extra small devices (phones, 600px and down) /
@media only screen and (max-width: 600px) {...}

/ Small devices (portrait tablets and large phones, 600px and up) /
@media only screen and (min-width: 600px) {...}

/ Medium devices (landscape tablets, 768px and up) /
@media only screen and (min-width: 768px) {...}

/ Large devices (laptops/desktops, 992px and up) /
@media only screen and (min-width: 992px) {...}

/ Extra large devices (large laptops and desktops, 1200px and up) */
@media only screen and (min-width: 1200px) {...}

Orientation: Portrait / Landscape

Media queries can also be used to change layout of a page depending on the orientation of the browser.

You can have a set of CSS properties that will only apply when the browser window is wider than its height, a so called "Landscape" orientation:

@media only screen and (orientation: landscape) {
  body {
    background-color: lightblue;
  }
}

The web page will have a lightblue background if the orientation is in landscape mode.


Thanks for reading this article! ๐Ÿ˜Š

ย