MediaClasses

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…


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


Print Share Comment Cite Upload Translate Updates
APA

Kolja | Sciencx (2022-04-02T07:49:36+00:00) MediaClasses. Retrieved from https://www.scien.cx/2022/04/02/mediaclasses/

MLA
" » MediaClasses." Kolja | Sciencx - Saturday April 2, 2022, https://www.scien.cx/2022/04/02/mediaclasses/
HARVARD
Kolja | Sciencx Saturday April 2, 2022 » MediaClasses., viewed ,<https://www.scien.cx/2022/04/02/mediaclasses/>
VANCOUVER
Kolja | Sciencx - » MediaClasses. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/04/02/mediaclasses/
CHICAGO
" » MediaClasses." Kolja | Sciencx - Accessed . https://www.scien.cx/2022/04/02/mediaclasses/
IEEE
" » MediaClasses." Kolja | Sciencx [Online]. Available: https://www.scien.cx/2022/04/02/mediaclasses/. [Accessed: ]
rf:citation
» MediaClasses | Kolja | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.