I have this code:
@media screen and (max-width: 570px) { #header { .flex-wrap(wrap); .justify-content(center); #headerTitles { margin-top: 1rem; } } } @media screen and (min-width: 571px) and (max-width: 950px) { #header.authenticated { .flex-wrap(wrap); .justify-content(center); #headerTitles { margin-top: 2rem; } } }
Is there a way that I can use Javascript (not jQuery) to dynamically add or remove a class to the to represent the two different sizes and then recode this something like:
.small #headerTitles { margin-top: 1rem; } .large #headerTitles { margin-top: 2rem; }
If this works then can someone comment as to if using Javascript is a better way to do this?
Using Media Queries With JavaScriptThe window. matchMedia() method returns a MediaQueryList object representing the results of the specified CSS media query string. The value of the matchMedia() method can be any of the media features of the CSS @media rule, like min-height, min-width, orientation, etc.
@media is the actually media query. The word screen is adding the 'conditions' to the media query. So @media screen is telling the media query to apply (whatever other conditions) to screens. For example, @media screen and (max-width: 360px) will target only screens with a max-width of 360px.
matchMedia() The Window interface's matchMedia() method returns a new MediaQueryList object that can then be used to determine if the document matches the media query string, as well as to monitor the document to detect when it matches (or stops matching) that media query.
Media queries allow you to not only vary viewport dimensions based on screen size, but they can also help you set different style properties for different devices, including color schemes, font styles, motion settings and animations, borders and spacing, and almost any other CSS property you can think of.
You can use window.matchMedia()
for media queries in javascript.
for example
var mq = window.matchMedia( "(max-width: 570px)" ); if (mq.matches) { // window width is at less than 570px } else { // window width is greater than 570px }
Please refer the below links for better understanding
https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia http://www.sitepoint.com/javascript-media-queries/
Updated as per comment
Please refer the plunker: "http://plnkr.co/edit/wAKFEFz0NU6ZaEmywlgc?p=preview"
For better understanding: "http://www.javascriptkit.com/javatutors/matchmediamultiple.shtml"
For web browser support information: "https://hacks.mozilla.org/2012/06/using-window-matchmedia-to-do-media-queries-in-javascript/"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With