Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add class or other attribute using media query

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?

like image 827
Alex K Avatar asked Feb 22 '13 11:02

Alex K


People also ask

Which attribute is used to implement a media query?

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.

How do you add an element to a media query in HTML?

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.

Can you use CSS variables in media queries?

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.

Do media queries add specificity?

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.


2 Answers

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.

  • http://lesscss.org
  • http://sass-lang.com

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.

SASS

.some-style { background-color:red; }

@media screen and (min-device-width: 480px) {
    body {
        @extend .some-style;
    }
}
like image 120
Bart Avatar answered Sep 27 '22 00:09

Bart


A JavaScript solution

if (window.matchMedia("(min-device-width: 480px)").matches {
    // modify dom
}
like image 20
Synesso Avatar answered Sep 23 '22 00:09

Synesso