Using Media Queries in Magento 2

cssmagento2

I'm trying to add a simple responsive grid into magento 2 by adding it into an additional stylesheet.

This does work on mobiles and when using inspect element in chrome however if I do not inspect element and resize the chrome window to test a narrow viewport below 767px the rule is not applied. This is making is very hard for me to diagnose because as soon as i click inspect element everything starts working as expected.

Example rule:

@media all and (max-device-width : 767px) {
    .col-4 {
        width: 100%;
        border-right:0px;
    }
}

Best Answer

I'm not entirely sure what your problem/question is?

I'm going to presume you mean your grid is only working on mobile and when you have inspect element open.

This is exactly what you're code is informing the browser to do, when the browser is 767px or under .col-4 will be fully width. When it's over 767px it will either do nothing or fall back to the original styling.

I'll take a guess that you have your inspect element panel attached to the side of your browser? This will cause the browser window to narrow hence why the media query is applying.

If you want this CSS to apply at all times just remove the media query like so:

.col-4 {
    width: 100%;
    border-right:0px;
}

Related notes

If you're using the default LESS styling for Magento 2 there are already media queries you can use:

//
//  Common (Both desktop and mobile)
//  _____________________________________________
& when (@media-common = true) {

}


//
//  Mobile
//  _____________________________________________

.media-width(@extremum, @break) when (@extremum = 'max') and (@break = @screen__m) {

}

//
//  Tablet
//  _____________________________________________

.media-width(@extremum, @break) when (@extremum = 'min') and (@break = @screen__m) {

}

//
//  Desktop
//  _____________________________________________

.media-width(@extremum, @break) when (@extremum = 'min') and (@break = @screen__l) {

}

Also, I would avoid using max-device-width unless you know this is exactly what you need. For almost all use cases max-width is what you want. See here for more info.