Skip to main content

Media Queries in CSS

Media Queries in CSS

Media queries are an essential tool in CSS for making responsive and adaptive web designs. They allow you to apply CSS rules based on a device's general type (such as print vs. screen), specific characteristics (like the width of the viewport), and environmental conditions (like ambient light conditions).

What are Media Queries?

Media queries consist of a media type and zero or more expressions that check for the conditions of certain media features. Media queries are used in the CSS to modify the styles based on these conditions.

@media screen and (min-width: 800px) {
body {
background-color: lightgreen;
}
}

In the above example, the background color of the body will change to lightgreen when the viewport is 800 pixels or wider.

How to Use Media Queries

To use media queries, you start with the @media rule followed by the type of media. The most common media types are all, print, screen, and speech.

  • all is used for all media type devices
  • print is used for printers
  • screen is used for computer screens, tablets, smart-phones, etc.
  • speech is used for screenreaders that "reads" the page out loud

The media type is then followed by an expression to check for certain conditions about the media features. Common media features are width, height, and orientation.

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

In the above example, the background color of the body will change to lavender when the viewport is 600 pixels or narrower.

Breakpoints in Media Queries

Breakpoints are the point a which your site's content will respond to provide the user with the best possible layout to consume the information. When the condition inside the media query is triggered, the CSS inside the media query takes effect.

You can have as many breakpoints as you want in your stylesheet. Common dimensions for breakpoints are:

  • 480px (smartphones in landscape orientation)
  • 576px (phablets)
  • 768px (tablets in portrait orientation)
  • 992px (tablets in landscape orientation and small desktop screens)
  • 1200px (desktops and laptops)
/* For desktop: */
body {
background-color: blue;
}

/* For tablets: */
@media screen and (max-width: 992px) {
body {
background-color: green;
}
}

/* For mobile phones: */
@media screen and (max-width: 576px) {
body {
background-color: yellow;
}
}

In the above example, the background color of the body will change based on the width of the device's screen.

Conclusion

Media queries in CSS are a powerful tool for creating responsive designs. By using them, you can ensure that your website looks great on all devices, regardless of their screen size or orientation. Start experimenting with media queries and see the difference they can make in your web designs.