The best option would be to have two sets of media queries which are only applied based on a parent class being present.
@media (max-width: 600px) {
.w600 .myDiv{
color:red;
}
}
@media (max-width: 400px) {
.w400 .myDiv{
color:red;
}
}
You could then add/remove w600
or w400
to the body
class to allow the required media query to work.
Using jQuery this could be done like:
$("body").addClass("w600")
.removeClass("w400");
I appreciate you may have more than just one style and would therefore like to reduce code duplication.
In which case you could 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();
}
}
Which would 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;
}
}