M2: Media Query Hell

Published on 07 Jun 2019 , edited on 13 Jun 2019

Nothing is ever easy with Magento, and the same goes for the pretty much modern and straightforward CSS3 media queries. Because Magento is a smart system, and it has smart implementations for things. But it also has very poor documentation on these smart things. Which kind of makes them frustrating, dumb things.

Magento 2 goes all-in on the mobile-friendly/mobile-first trend we have nowadays. Great! CSS3 has made this very easy and with a CSS preprocessor such as LESS or SASS it is as easy as this;

.some-mobile-only-element {
    display:block;
     @media only screen and (min-width: 768px) {
         display:none;
     }
}

In this example we put our basic styling first, which is aimed towards mobile usage. Then we use a media query inside the selector to apply differentiating styles for desktop (>= 768px). Easy peasy.

“OK” says Magento, “we got this”, and they introduce their own mixin;

  .media-width(@extremum, @break) when (@extremum = 'max') and (@break = @screen__s) {
      [your styles]
  }

Where the @extremum is either min or max, and the @break has some predefined variables standing for basic pixel values. And apart from being a way-too-long-for-a-mixin-string, it doesn’t work as easy as the simple situation listed above.

This has to do with the way Magento tries to optimize their code by, for example, not including any code for desktop on mobile and visa versa. Which is a good idea, to be sure, but the workflow is a terrible, terrible hell.

So, what now?

Someone posted my exact case as a bug, which was later discarded as “not a bug becuz”. Here is the corresponding Stack Overflow topic. And I want to believe this is expected behavior and I’m interpreting the vague docs completely wrong. So what we’ll have to do is figure out what the Magento devs meant for us to do, which in and of itself is a struggle.

As it turns out, it’s rather simple but still stupid if you ask me; you can’t use the Magento specific media-width mixins nested. Which is the most preferable way to use them; to keep your repsonsive CSS clean and structured. Instead it only works not-nested, so you have to call each class for each media query. So instead of overwriting specific styles inside a class like I’d want to do;

.myclass {
    display:block;
    width:250px;
    @mediaquerymixin(desktop) {
       width:500px;
    }
}

You’d have to do it like this

@mediaquerymixing(mobile) {
    .myclass {
        display:block;
        width:250px;
    }
}
@mediaquerymixin(desktop) {
    .myclass {
        width:500px;
    }
}

Which is kind of awful in my opinion. But the functionality the Magento media query provides beyond this is worth it, I guess.

M2M2

Moving To Magento Two; A big move from multiple Magento 1.9.x systems to Magento 2.x. Documented every step chronologically (currently ongoing!).

All categories

All tags

All posts