Is Chrome rounding media query em units wrong?

2019-08-10 02:05发布

问题:

I have set up media query break points as follows:

@media screen and (max-width:48em){
    /* phone */
}
@media screen and (min-width:48.063em){
    /* tablet*/
}

I got the 48.063em value from some PX to EM calculator (I was told to use em-units for some reason, but that is outside of this question), and it is working ok in firefox, but in chrome, it seems that browser width of 769px falls BETWEEN those max-width / min-width values, and neither is applied to the page. I know this can be fixed by setting that min-width to 48.01em, don't worry about that. I have seen 48.063em used in some tutorials also.

Can someone confirm if this is a bug in chrome, or an error in my logic?

回答1:

I've had this exact problem and I think you are correct that your width is falling between the specified values and therefore neither style is applied. I think the solution is to remove your phone media query and just have the phone styles at the top level, like so:

/* phone styles */

@media screen and (min-width:48.063em){
    /* tablet styles */
}

In this case your phone styles will be applied unless the width is 48.063em or above, in which case the phone styles will be overridden by similar ones in the media query (mobile first design). This way you only have a single cut-off point. You could further extend this to larger devices in the same way:

@media screen and (min-width:100em){
    /* even larger styles */
}

If you look at the CSS for Foundation you will see this approach, which is what helped me figure it out. Why the original code seems to work in browsers other than Chrome, I do not know.