CSS Media Queries for Responsive Design: A Complete Guide

CSS media queries poster

CSS media queries are a crucial tool for creating responsive designs, as they allow developers to apply specific styles based on the user’s device or screen size. In this article, we will cover everything you need to know about CSS media queries for responsive design.

What are CSS Media Queries?

CSS media queries are a CSS feature that allows developers to apply specific styles to elements based on the user’s device or screen size. Media queries work by evaluating the user’s device or screen characteristics, such as width, height, and orientation, and applying CSS styles accordingly.

Media queries use the @media rule to define the conditions under which the styles should apply. For example, @media (min-width: 768px) { ... } applies the styles inside the curly braces only when the device or screen has a minimum width of 768 pixels.

Using CSS Media Queries

To use CSS media queries, first, define the conditions under which the styles should apply using the @media rule. Then, add the CSS styles inside the curly braces.

Here’s an example:

@media (max-width: 600px) {
  body {
    font-size: 14px;
  }
}

In this example, we define a media query that applies to devices or screens with a maximum width of 600 pixels. The styles inside the curly braces set the font size of the body element to 14 pixels.

Best Practices for Using CSS Media Queries

Here are some best practices for using CSS media queries:

  • Use relative units, such as em or rem, for defining styles, as they are more flexible and adapt better to different screen sizes.
  • Use the max-width condition when following desktop-first approach design and min-width if you follow mobile-first approach design.
  • Use breakpoints that match the most common device sizes, such as 576px, 768px, 1024px, 1216px, and 1400px.
  • Avoid nesting media queries, as it can make the CSS code harder to read and maintain.
author's bio photo

Hi there! I am Avic Ndugu.

I have published 100+ blog posts on HTML, CSS, Javascript, React and other related topics. When I am not writing, I enjoy reading, hiking and listening to podcasts.