Add class or other attribute using media query

♀尐吖头ヾ 提交于 2019-12-21 03:46:36

问题


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?


回答1:


Check out Enquire.js. Lightweight, pure JavaScript library for handling media queries. Looks pretty cool.




回答2:


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;
    }
}



回答3:


A JavaScript solution

if (window.matchMedia("(min-device-width: 480px)").matches {
    // modify dom
}



回答4:


take a look at conditionizr this could be what your looking for http://conditionizr.com/




回答5:


For this also can help Modernizr - can detect even if svg enabled or other features is enabled.

http://modernizr.com/



来源:https://stackoverflow.com/questions/15022888/add-class-or-other-attribute-using-media-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!