CSS Media Queries

css-logo

What is a Media Query

Responsive web design is a very important topic for web developers as every year there are more and more users using smartphones and tablets. To have a responsive web site, it is important to be "Design for Mobile First". Mobile-first means designing for mobile before designing for other devices like desktop, tablet, etc. For that purpose, it is important to know what it is and how to use media queries. Media Query is a CSS feature introduced in CSS3, which allows us to specify when certain CSS rules should be used. With media queries, we can easily apply unique CSS rules to specific devices like Laptop, Tablet, Mobile, etc.

How to make a Media Query

To make a media query we need to use the keyword @media and declare the breakpoint (screen size), and set the CSS rules inside the {}. Let's see how simple media query looks like:

@media only screen and (max-width: 600px) {
  body {
    background-color: blue;
  }
}

In our example above we make a media query for screens with a maximum width of 600px so if the browser window is 600px or smaller, set the background color to blue. We can also use an external stylesheet for media queries, the syntax looks like this:

<link rel='stylesheet' media='screen and (max-width: 600px)' href='css/small.css' />

Device Breakpoints

There are a lot of screens and devices with different widths and heights, so it is not possible to have exact breakpoints for every device available. To keep it simple we will use a couple of groups.

/* 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) {}

Device Breakpoints Example (Source: w3school)

Browser Support for Media Queries

Media queries have very good browser support for min and max widths, almost all major browsers like Chrome, Firefox, Safari, iOS Safari, Android Browser, Opera and Internet Explorer from version 9 and above are currently are supporting media queries.




#css #html

Author: Aleksandar Vasilevski |