This content originally appeared on DEV Community and was authored by Kolja
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" }
];
With the following query, we find out the appropriate width of the screen:
if (window.matchMedia(`(max-width: ${breakpoint.width})`).matches)
Now just add the class (don't forget to delete the old one first) to the body tag:
document.body.removeAttribute("class");
document.body.classList.add(breakpoint.class);
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);
A small example here in this codepen.
A somewhat larger one in this template on GitHub.
This content originally appeared on DEV Community and was authored by Kolja
Kolja | Sciencx (2022-04-02T07:49:36+00:00) MediaClasses. Retrieved from https://www.scien.cx/2022/04/02/mediaclasses/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.