Search code examples
htmlcssmediaviewportresponsive

My site appears zoomed in when opened on the phone


HEAD

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

CSS

@media (max-width: 600px){
body{position: absolute; top: 0px; left: 0px; width: 420px;}

My site appears zoomed in when opened on the phone
Screenshots is here
How can I fix?


Solution

  • You are setting the body's width to be wider than the phone's screen (since your viewport tag causes "px" units to not be 1:1 so 1 pixel on the phone doesn't correspond to 1 px unit). You should either use relative values for your body style

    @media (max-width: 600px){
        body{
            position: absolute; 
            top: 0; 
            left: 0; 
            width: 100vw;
            max-width: 420px;
        }
    }
    

    or create an extra @media query for devices narrower than 420px like this:

    @media (min-width: 420px) and (max-width: 600px){
        body{
            position: absolute; 
            top: 0; 
            left: 0; 
            width: 420px;
        }
    }
    
    @media (max-width: 420px){
        body{
            position: absolute; 
            top: 0; 
            left: 0; 
            right: 0;
        }
    }
    

    Edit:

    Here's another approach with a dynamic viewport tag:

    <meta id="viewport" name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <script>
    window.onload = function() {
        if(screen.width < 420){
            var viewport = document.getElementById('viewport');
            viewport.setAttribute('content', 'width=420, initial-scale=1');
        }
    }
    </script>