(Quick disclaimer: This tutorial assumes you have a bit of understanding of css and html but I tried my best to dumb things down as much as possible.)

What is a media query?

Media queries let you change the way your website looks depending on the size or shape of the screen someone is using. This helps your website look good on anything from a phone to a computer monitor.

How Do Media Queries Work?

Media queries are written as part of your CSS and use the @media rule. For example:

@media (max-width: 600px) {
body {
background-color: #51d7ca;
  }
}
note: #51d7ca is the hex code for the color teal. you can find different colors' hex codes by using websites like HTML Color Codes, RedKetchup color picker, and Color Code Hex.

Live Example

Resize your browser window to see how the styles change based on the screen width:

This box changes style when the screen width is 600px or less!

Common Use Cases for Media Queries

Tips for Using Media Queries

  1. Start with a "mobile-first" approach: design for small screens first, then add styles for larger screens.
  2. Use em or rem units instead of px to make your designs more flexible.
  3. Test on multiple devices to ensure your media queries work properly. Here are some free tools to help:
  4. Most modern browsers, like Chrome, have built-in developer tools with device emulators. These allow you to test your media queries on various devices without needing the devices themselves.
It's a good practice to place media queries at the bottom of your CSS file or below your regular CSS if you're using one HTML document. This ensures they override earlier styles when necessary, since CSS applies rules in order. This is called 'cascading,' which means CSS reads the rules from top to bottom. If two rules try to style the same thing, the rule written first will be ignored. For example:

/* Style1 */
h1 {
color: green;
}
/* Style2 */
h1 {
color: orange;
}

Style 2 always overrides Style 1 because it's the last in the list. So the color of the h1 headings would be orange, even though both rules are trying to change the h1 heading color.

The same would apply if you added a Style 3 and set Style 3 to change the h1 header to pink. In that case, the h1 header would be pink.

Breakpoints

Breakpoints are specific screen widths where your site layout should adapt to offer the best user experience. Common breakpoints include: