Introduction to Media Queries

What media queries are and why they matter

What are Media Queries?

Media queries are a CSS feature that allow content rendering to adapt to different screen sizes, resolutions, or device characteristics.

Basic Syntax


@media (max-width: 768px) {
  body {
    background-color: lightblue;
  }
}
    

Note: You can target various properties like min-width, orientation, aspect-ratio, etc.

Types of Media Features

Commonly used query conditions

Screen Width and Height


@media (min-width: 1024px) and (max-width: 1200px) {
  .container {
    padding: 2rem;
  }
}
    

Orientation


@media (orientation: landscape) {
  body {
    flex-direction: row;
  }
}
    

Resolution


@media (min-resolution: 2dppx) {
  .icon {
    background-image: url('high-res.png');
  }
}
    

Logical Operators

Using and, or, not in media queries

Using AND


@media (min-width: 600px) and (orientation: portrait) {
  /* styles */
}
    

Using NOT


@media not all and (monochrome) {
  /* styles for color devices */
}
    

Best Practices

Writing clean and efficient queries

Mobile First Approach


/* Default (mobile) */
body {
  font-size: 14px;
}

/* Larger screen */
@media (min-width: 768px) {
  body {
    font-size: 16px;
  }
}
    

Avoid Redundancy

Group shared styles outside the media query to reduce duplication.

Media Query Table

Reference for features and values

Supported Media Features

Feature Example Value Description
width 600px Viewport width
orientation landscape Device orientation
resolution 300dpi Screen DPI

Image Use Case

Media query behavior with image layouts

Responsive Grid Image Container

sample1 sample2 sample3 sample4

Related Query


@media (max-width: 768px) {
  .image-container {
    grid-auto-flow: row;
  }
}