I am using a component-based CSS style, so I have been using mixins to allow me to use media queries without accidentally compiling hundreds of them. This is what I am doing for screen sizes:
Main file:
.mq-medium() {}
@import //other files
@media only screen and (min-width: 600px) {
.mq-medium;
}
Another file:
.mq-medium() {
.banner {
width: 50%;
}
}
This can be used several times and results in grouped queries.
The Problem
I am trying to do the same thing for retina background-image queries, and am having trouble figuring out how to do so. This is my test:
.mq-retina() { }
.background-image(@image){
@filename: ~`/(.*)\.(jpg|jpeg|png|gif)/.exec(@{image})[1]`;
@extension: ~`/(.*)\.(jpg|jpeg|png|gif)/.exec(@{image})[2]`;
background-image: ~`"url(@{filename}.@{extension})"`;
.mq-retina() {
& {
background-image: ~`"url(@{filename}_2x.@{extension})"`;
background-size: 100%;
}
}
}
.lol {
.background-image("test.jpg");
}
@media only screen and (min-device-pixel-ratio: 1.5) { //shortened for this example
.mq-retina;
}
But the output is just
.lol {
background-image: url(test.jpg);
}
I believe this has to do with scoping issues, but am unsure how to resolve this. How can I add to the .mq-retina()
mixin without scoping problems?
(See comments above for context of this solution). I'd say that a price for non-repeating media queries will always be "repeating something else then". I.e. it either has to be the media depended property as in:
Or the media depended selector itself, as in:
---
P.S. For this simplified case it is also possible to modify the first example to get rid of repetitions, for example like this:
But that way it actually becomes a variant of the second example (where more complex code will lead to repeated selectors in the generated CSS because you won't want to put all properties into
.mq-common
), not counting that the whole thing also turns to be quite head-scratching.---
P.P.S. And at last, it is finally possible to consolidate "everything" (in the generated CSS) by introducing another level of indirection, but the source code itself becomes too verbose to be actually usable in practice. (In this example I'll break it into two files for a bit more clear code, but that's not really required - the imported file can be written as one big mixin):