A better option would be to have two sets of media queries that apply only based on the parent class.
@media (max-width: 600px) { .w600 .myDiv{ color:red; } } @media (max-width: 400px) { .w400 .myDiv{ color:red; } }
Then you can add / remove w600 or w400 to the body class to allow the required media request to work.
Using jQuery, this can be done like this:
$("body").addClass("w600") .removeClass("w400");
I appreciate that you may have more than one style, and therefore he would like to reduce code duplication.
In this case, you can use a CSS transpiler such as Less with mixins:
@mediaqueryruleset:{ .myDiv{ color:red; } .myOtherDiv{ color:blue; } } @media (max-width: 600px) { .w600 { @mediaqueryruleset(); } } @media (max-width: 400px) { .w400 { @mediaqueryruleset(); } }
What will be output:
@media (max-width: 600px) { .w600 .myDiv { color: red; } .w600 .myOtherDiv { color: blue; } } @media (max-width: 400px) { .w400 .myDiv { color: red; } .w400 .myOtherDiv { color: blue; } }
Curt
source share