A Complete Guide to CSS Media Queries

CSS Media Queries allow us to create responsive designs that adapt to different screen sizes and devices. In this guide, we’ll explore how to use media queries in CSS to create responsive layouts.

Syntax

A media query consists of a media type and one or more expressions that define the conditions for the media query to apply. The syntax for a media query is as follows:

css
@media media-type and (expression) {
/* Styles go here */
}

The media-type can be any of the following:

  • all: Applies to all devices.
  • screen: Applies to devices with a screen.
  • print: Applies to devices that are meant to be printed.
  • speech: Applies to screen readers and similar devices.

The expression can be any of the following:

  • width: The width of the viewport.
  • height: The height of the viewport.
  • orientation: The orientation of the device (landscape or portrait).
  • aspect-ratio: The aspect ratio of the viewport.
  • device-width: The width of the device screen.
  • device-height: The height of the device screen.
  • device-aspect-ratio: The aspect ratio of the device screen.

You can combine these expressions with logical operators like and, not, and only to create more complex media queries.

Examples

Here are some examples of media queries:

Responsive Font Size

css
h1 {
font-size: 48px;
}

@media screen and (max-width: 768px) {
h1 {
font-size: 36px;
}
}

@media screen and (max-width: 480px) {
h1 {
font-size: 24px;
}
}

In this example, we use media queries to change the font size of the h1 element based on the width of the viewport. When the viewport is less than or equal to 768px, the font size is set to 36px, and when it’s less than or equal to 480px, the font size is set to 24px.

Responsive Layout

css
.container {
display: flex;
flex-wrap: wrap;
}

.container > div {
width: 25%;
}

@media screen and (max-width: 768px) {
.container > div {
width: 50%;
}
}

@media screen and (max-width: 480px) {
.container > div {
width: 100%;
}
}

In this example, we use media queries to create a responsive layout that adapts to different screen sizes. When the viewport is less than or equal to 768px, the width of each div element is set to 50%, and when it’s less than or equal to 480px, the width is set to 100%.

High-Resolution Images

css
@media screen and (-webkit-min-device-pixel-ratio: 2),
screen and (min-resolution: 192dpi) {
/* Styles for high-resolution devices */
}

In this example, we use media queries to apply styles to high-resolution devices like retina displays. We use two expressions to target high-resolution devices: -webkit-min-device-pixel-ratio: 2 for WebKit browsers, and min-resolution: 192dpi for other browsers.

Conclusion

Media queries are an essential tool for creating responsive designs that adapt to different screen sizes and devices. By using media queries, we can create layouts that look great on any device, from large desktop screens to small mobile devices.