CSS max-width has inaccurate pixel precision

北战南征 提交于 2021-01-02 12:55:20

问题


I have an issue with max-width media rule. I test to hide the elements on different max-width values and the behavior is inconsistent. I have tested 4 scenarios varying in the screen width.

  • Scenario 1: Screen width is 638px: This matches my expectation.
  • Scenario 2: Screen width is 639px: This is wrong! I expect column639 still to be hidden!
  • Scenario 3: Screen width is 640px: This matches my expectation.
  • Scenario 4: Screen width is 641px: This matches my expectation.

Question:

What causes the pixels inaccuracy in the Scenario 2 and why is 639px value treated differently than others?

Reproducibility:

Strangely, it cannot be reproduced everywhere (resize the window to the width of 693px:

  • Google Chrome: I can reproduce, (86.1.6938.200, 64-bit)
  • Mozilla Firefox: I can reproduce, (87.0.4280.88, 64-bit)
  • JSFiddle: I cannot reproduce (all scenarios as expected): https://jsfiddle.net/vop23ang/
  • CodePen: I can reproduce (all scenarios as expected, you need to Change View to resize horizontally): https://codepen.io/nikolas-charalambidis/pen/YzGYPGE

Code:

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <h1>max-width issue</h1>
        <div class="column column639">
            <h2>Column 1</h2>
        </div>
          
        <div class="column column640">
            <h2>Column 2</h2>
        </div>
    </body>
</html>
.column {
    width: 100%;
    background-color: cyan;
}

@media screen and (max-width: 639px) {
    .column639 {
        visibility: hidden;
    }
}

@media screen and (max-width: 640px) {
    .column640 {
        visibility: hidden;
    }
}

Scenarios:

Scenario 1: Screen width is 638px:

Scenario 2: Screen width is 639px:

Scenario 3: Screen width is 640px:

Scenario 4: Screen width is 641px:


回答1:


max-width is including the width limit you provide: equal or narrower.

For example, this CSS will apply styles only if your browser's viewport width is equal to or narrower than 12450px:

@media (max-width: 12450px) { ... }

Documentation


I made a codepen to test that. Try it.

The result is what I would expect...




回答2:


This was reported and accepted as a bug reproducible on multiple versions. Currently, it's on review by the development team.

Follow the issue #1162102 for more details, however, I will update the answer once the issue is resolved, though.



来源:https://stackoverflow.com/questions/65470317/css-max-width-has-inaccurate-pixel-precision

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!