Domanda

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?

È stato utile?

Soluzione

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!

Altri suggerimenti

You can use !important or you can make a seperate css file then declare it in app/frontend/Your_Vendor/Your_theme/Magento_Theme/layout/default_head_blocks.xml like this:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <head>
            <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
            <css src="css/your_css_file.css" />
        </head>
</page>

and your css file location is: app/frontend/Your_Vendor/Your_theme/web/css/your_css_file.css

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a magento.stackexchange
scroll top