Skip to content

Media Queries

Change code depending on screen size

  • Lesson
  • 1 min read
  • 3 of 4 in this chapter

Media queries are a useful tool for designing responsive sites. They allow you to change the code depending on the size of the screen.

Here's how to create a media query:

CSS
@media (min-width: 500px) {
    h1 {
        font-size: 40px;
    }
}

The code inside this media query will only apply on devices with a screen larger than 500px. Here, the heading will only be 40 pixels tall on large screens.

If you want to specify an upper bound instead of a lower one, use max-width instead of min-width:

CSS
h1 {
    font-size: 2em;
}
@media (max-width: 500px) {
    h1 {
        font-size: 0.7em;
    }
}

In the CSS document, media queries should go after the original CSS for the same selectors, as you can see done in the example above. This way, the media query overrides the CSS that comes first, and the CSS that comes first only applies in cases were the media query doesn't.