Responsive Design Order in Magento 2 – CSS Guide

cssmagento2rwd

I've just created a new theme that extends from Magento Blank, and within the file _theme.less I did something like this:

h1 {
  font-size: 24px;
}  

@media (max-width: 768px) {
  h1 {
    font-size: 18px;
  }  
}

@media (max-width: 480px) {
  h1 {
    font-size: 12px;
  }  
}

However, the mobile styles are not being applied. I opened the styles-m.css source code and I found out that the desktop styles are at the bottom, overriding all of the styles above them.

@media (max-width: 480px) {
  h1 {
    font-size: 12px;
  }  
}

@media (max-width: 768px) {
  h1 {
    font-size: 18px;
  }  
}

h1 {
  font-size: 24px;
}

What am I doing wrong here?

Best Answer

You should build your media queries the proper way the Magento UI library expects it as Magento will build a style file for mobile (styles-m.css) and for desktop devices (styles-l.css). I think the issues you currently experience can be traced back to this. You should also approach this in a mobile-first manner. Try this:

.media-width(@extremum, @break) when (@extremum = 'max') and (@break = @screen__xs) {
  h1 {
    font-size: 12px;
  }  
}

.media-width(@extremum, @break) when (@extremum = 'max') and (@break = @screen__m) {
  h1 {
    font-size: 18px;
  }  
}

.media-width(@extremum, @break) when (@extremum = 'min') and (@break = @screen__m) {
  h1 {
    font-size: 24px;
  }  
}

This way, the default size is 12px for small mobile devices, everything which is wider than 480px will have 18px and devices wider than 768px will be size 24px. These sizes are defined in lib/web/css/source/lib/variables/_responsive.less. You should definitely read the developer guide on the matter to understand how to effectively use these queries.

Also, make sure Magento 2 is set to development mode!

Related Topic