CSS Media Queries Tutorial

CSS media queries are used to create responsive web designs. They allow developers to apply different styles based on screen size, device type, or display resolution.

Responsive design ensures that websites look good and function properly on mobile phones, tablets, laptops, and desktop computers.

Media queries are an essential part of modern web development because users access websites from many different devices.

Using media queries, developers can change layouts, font sizes, and element positions depending on the device screen size.

Basic Media Query Syntax

A media query consists of a media type and one or more conditions.

CSS
Basic Media Query Syntax
@media (max-width: 768px) {
  body {
    background-color: lightgray;
  }
}

This example changes the background color when the screen width is 768 pixels or smaller.

Common Screen Size Breakpoints

Developers often use specific breakpoints to target different devices.

  • Mobile devices: up to 600px
  • Tablets: 601px to 768px
  • Small laptops: 769px to 1024px
  • Desktops: above 1024px

Mobile First Approach

The mobile-first approach means designing the website for mobile devices first and then expanding styles for larger screens.

CSS
Mobile First Example
body {
  font-size: 14px;
}

@media (min-width: 768px) {
  body {
    font-size: 18px;
  }
}

Responsive Layout Example

CSS
Responsive Layout Example
.container {
  display: grid;
  grid-template-columns: 1fr;
}

@media (min-width: 768px) {
  .container {
    grid-template-columns: 1fr 1fr;
  }
}

This example creates a single-column layout on mobile devices and a two-column layout on larger screens.

Media Query Features

Media queries can target several device features.

  • width
  • height
  • orientation
  • resolution
  • aspect-ratio

Orientation Example

CSS
Orientation Media Query
@media (orientation: landscape) {
  body {
    background-color: lightblue;
  }
}

This rule applies when the device screen is in landscape mode.

Best Practices for Media Queries

  • Use mobile-first design strategy.
  • Avoid too many breakpoints.
  • Test designs on multiple devices.
  • Use flexible layouts like Flexbox or Grid.
  • Optimize images for different screen sizes.

Conclusion

CSS media queries are essential for building responsive websites that work on all devices.

By adjusting styles based on screen size and device characteristics, developers can ensure a consistent user experience.

Mastering media queries is a key step toward becoming a skilled front-end developer.