< Back to CSS and Sass notes

Media Queries

Different types of useful CSS media queries for responsive styling

Resources:


By Viewport Size

Minimum

@media (min-width: 30em) { ... }
@media (min-height: 30em) { ... }

Maximum

@media (max-width: 30em) { ... }
@media (max-height: 30em) { ... }

Aspect Ratio

@media (aspect-ratio: 11/5) { ... }
  // Height of 10rem and width of 22rem
  // Also height of 22rem and width of 10rem

Orientation

@media screen and (orientation: landscape) {
  .layout { flex-direction: row; } // Horizontal layout for more horizontal screens
}

@media screen and (orientation: portrait) {
  .layout { flex-direction: column; } // Vertical layout for more vertical screens
}

By Viewport Type

Color

p { color: black } // Default, grayscale devices

@media (color) {
  p { color: red } // For devices with at least basic colors
}

@media (min-color: 8) {
  p { color: #24ba13; } // Devices with 8 bits per color component (larger color variety)
}

Resolution

@media (resolution: 50dpi) { ... } // Only for devices with 50dpi

@media (min-resolution: 300dpi) {
  .hide-on-high-dpi { display: none } // Hides elements on high DPI devices
}

@media (max-resolution: 300dpi) {
  .hide-on-low-dpi { display: none } // Hides elements on low DPI devices
}

Screen

@media screen { ... }

Print

@media print { ... }

Speech

@media speech { ... }

All

@media all { ... }

Chaining Media Queries

You can use different logic for how CSS should apply all these queries.

“And”

@media screen and (min-width: 30rem) { ... }

“Or”

@media screen, (min-width: 30rem) { ... }

“Not”

@media not screen { ... }
@media not screen and (min-width: 30rem) { ... } // Works if it's not a screen, AND the width is larger than 30rem
@media not screen, (min-width: 30rem) { ... } // Works if it's not a screen, OR the width is larger than 30rem

@supports

.layout {
  display: block;
}

@supports (display: grid) {
  .layout {
    display: grid;
  }
}