Watch CSS3 Media Queries in JavaScript

- 2 minutes read

CSS3’s media queries are an essential element of responsive web design.

Here’s a simple media query example that increases the font size on screens with larger widths:

p {
    font-size: 14px;
@media screen and (min-width: 768px) {
    p {
        font-size: 18px;

While media queries provide a handy way for responsively updating CSS values, you might also want to perform certain actions based on the current screen width using JavaScript as well.

This is a snippet that recreates the above CSS example in JavaScript:

const update = (mediaQuery) => 
        ? document.querySelectorAll(`p`).fontSize = `18px`
        : document.querySelectorAll(`p`).fontSize = `16px`;

const query = window.matchMedia(`screen and (min-width: 768px)`);


You can also listen for changes to query:


And you can of course include whatever code you want in the update function, and you can pass any other kind of valid media query to it as well. This is just an example.

Link to this section Getting the current screen dimensions

If you just want to get the dimensions of the browser window in JavaScript, there is a better way:

const width = window.screen.width;

const height = window.screen.height;

The above code will return the integer value of the screen width and height, in pixels. However, the returned values won’t automatically update each time the screen is resized.

Link to this section Conclusion

Anyway, I hope you found this quick little snippet useful!

It’s great for running a function each time the screen is resized, among other things.