DEV Community 👩‍💻👨‍💻

Cover image for MediaClasses

Posted on


Wouldn't it be nice to be able to do without those ugly media-queries in CSS?
Just a class for the respective width and that's it?

No problem with a little Javascript!

First, we define the desired screen widths and the corresponding class names in an object:

const breakpoints = [
  { width: "36em", class: "small" },
  { width: "64em", class: "medium" },
  { width: "99em", class: "large" }
Enter fullscreen mode Exit fullscreen mode

With the following query, we find out the appropriate width of the screen:

if (window.matchMedia(`(max-width: ${breakpoint.width})`).matches)
Enter fullscreen mode Exit fullscreen mode

Now just add the class (don't forget to delete the old one first) to the body tag:

Enter fullscreen mode Exit fullscreen mode

Put all this into a small function and call it at the beginning and at every change of the viewport:

window.addEventListener("DOMContentLoaded", mediaClasses);
window.addEventListener("resize", mediaClasses);
Enter fullscreen mode Exit fullscreen mode

A small example here in this codepen.
A somewhat larger one in this template on GitHub.

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!