DEV Community

Gulshan
Gulshan

Posted on

CSS Media Query in Javascript

Quick Summary

CSS media queries are very effective and optimal for applying styles based on device properties and settings. We’re going to look at a feature in javascript that let’s us use CSS media queries in our JS.

What’s matchMedia?

matchMedia is a method available on the window object that can be used to match or track a CSS media query on the document. Read more about it on MDN.

Syntax

Taking a CSS media query for example

@media (max-width: 480px) {
  body {
    font-size: 16px;
    background-color: lightgray;
  }
}
Enter fullscreen mode Exit fullscreen mode

We would need what’s written after @media as it is

const matchMobileQuery = window.matchMedia("(max-width: 480px)");
Enter fullscreen mode Exit fullscreen mode

Testing it on the browser console, here’s what the matchMedia returns

demo of using match-media to toggle theme
So we can take the matches variable to check whether the query matched or not.

To Track a media query, we can add a change event listener on the same MediaQueryList object given by the matchMedia.

Let’s test this with an example of prefers-color-scheme media query

const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');

function handleChange(e) {
  if (e.matches) {
    console.log('Dark mode');
  } else {
    console.log('Light mode');
  }
}

mediaQuery.addEventListener('change', handleChange);
Enter fullscreen mode Exit fullscreen mode

We should see a console log whenever the color scheme changes

Screenshot of matchmedia object from browser console

When to use?

  • To replace window.innerWidth to find out what device we’re on

  • Replace any element size tracking with resizeObserver, if it can be solved with a media query

  • It’s not just for screen size—use it to react to dark mode, device orientation, and more

Thanks for reading!

If you made it till here, let’s hear your thoughts on this in the comments!

Top comments (0)