I'm currently using CSS media queries to target some small/medium screen devices like this:
@media screen and (min-device-width: 480px) {
...
}
@media screen and (min-device-width: 720px) {
...
}
This works as expected, and I can apply styles to some particular selectors, but.. What I was wondering is if there is a way to add a class or other attribute to a selector based on media query.
Example of my thought:
@media screen and (min-device-width: 480px) {
body { addClass('body-iphone') }
}
Is there a way to do that with CSS or maybe JavaScript?
The @media rule is used in media queries to apply different styles for different media types/devices. Media queries can be used to check many things, such as: width and height of the viewport.
The Placement of Media Queries The internal method includes adding the <style> tag to the <head> tag of the HTML file, and creating the media query within the parameters of the <style> tag. The external method involves creating a media query in an external CSS file and linking it to your HTML file via the <link> tag.
If you're like me, you've probably been stretching CSS variables / custom properties to their limits while building your own design systems. But this "silver bullet" can lead to a nasty roadblock: you can't use them in media query declarations.
So there you have it, media-queries does not affect specificity. A media-query only decides whether the code inside it should be enabled or not.
It cannot be done with plain CSS.
Have a look at LESS or SASS. They are designed to make working with CSS more dynamic and flexible.
Once you use them. You can't live without them.
In case you want to add a existing class selector to the body on certain resolutions.
.some-style { background-color:red; }
@media screen and (min-device-width: 480px) {
body {
@extend .some-style;
}
}
A JavaScript solution
if (window.matchMedia("(min-device-width: 480px)").matches {
// modify dom
}
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