Why is CSS min-width causing my responsive site to

2019-08-03 23:11发布

I'm building a responsive website and I'm having a problem with it which means that when I view it on a mobile, it's automatically zoomed in by a small amount. I can zoom out to view the whole width of the page, but when I click on a link to another page, the new page loads in slightly zoomed in as well (maybe by 10% or so).

I've set an appropriate viewport which should deal with the problem:

<meta name="viewport" content="width=device-width, initial-scale=1" />

I also have set a minimum width on the body, which is necessary as below this width the site layout breaks:

body {
    min-width: 400px;
}

Without the min-width the site works fine on mobile devices, but with the min-width, the pages load slightly zoomed in. I've tried this on Chrome and the stock browser on Android (on a Galaxy S3 and Galaxy Nexus) with the same results, so it seems I am misunderstanding something rather than having discovered a bug.

Ultimately I want the site fully zoomed out (initial-scale=1) and the minimum display width set at 400px so I don't need to worry about layouts at tighter widths. Is this even achievable?

2条回答
Viruses.
2楼-- · 2019-08-03 23:37

You can use this to prevent zooming.

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1,user- scalable=0"/>

But I don't think it's a good idea keep

body
{
   min-width: 400px;
}

because the content will overflow in a smaller viewport. Your zooming problem may be from the combination of

body
{
   min-width: 400px;
   overflow: hidden;
}

so it seems like it's zoomed in.

查看更多
家丑人穷心不美
3楼-- · 2019-08-03 23:40

Okay, I've managed to find an adequate solution to this problem. The issue is that I was setting the viewport to the device-width, which generally seems to be a good thing to do.

The problem arises when the device width is lower than the minimum width set for my site (400px in this instance). So, for example, if the device width is 320px, the viewport is set to this width resulting in the web pages being about 80px too large for the mobile screen.

The solution is some JavaScript to change the viewport width from device-width to 400 in instances where the window width is less than or equal to 400 pixels. This snippet of code addressed the problem:

<meta id="myViewport" name="viewport" content="width=device-width" />
    <script>
        window.onload = function () {
            if(window.innerWidth <= 400) {
                var mvp = document.getElementById('myViewport');
                mvp.setAttribute('content','width=400');
            }
        }
     </script>
查看更多
登录 后发表回答