Search code examples
cssresponsive-designmedia-queries

auto scale webpage to fit mobile screen


Lets say I've prepared one mobile version for all smartphones and I've chosen 320px for my banner - background image (320x177), the code looks like this:

@media only screen and (max-width: 400px) and (orientation : portrait) {
    body {margin: auto; max-width:320px}
    #banner {height: 177px; max-width: 100%; background-position: center top; background-repeat: no-repeat;  background-size: contain;}
    #banner {background-image: url("background320.jpg"); border:1px solid black;}
    #banner span {margin:15% 0 0 10%}   
    #content {max-width: 100%; height: 1000px; border:1px solid black;}
}

<div id="banner">
   <span>Banner Title</span>
</div>
<div id="content"> Some content </div>

In this case if the screen is larger (like my phone 360px wide portrait), I get white stripes on the left and right side. I don't want make another mobile version for 360px, but I just want scale up the page to fit the screen (the same as you do manually with two fingers). If the screen is smaller then would scale down to fit the window. How to do it? OR how should it be this done properly referring to this example?

EDIT: I tried to use background-size: 100% 100% to keep background aspect ratio when showing on different screen resolution, but there is always problem with height. If I don't set up static height height:177px then the background height is only as high as the content inside or doesn't appear at all if there is no content inside it. The static height is also bad when it must be shown on a different screen resolutions. How do you solve this without making additional mobile versions?


Solution

  • Use background-size:cover or background-size:100%, instead of background-size:contain.

    Edit: Sounds like you want the div to keep the aspect ratio of the image. If so, you can use zero height on the div with vertical padding:

    #banner {
        background-image: url(http://placehold.it/320x177);
        background-size: 100% 100%;
        padding-top: 55.3125%;
    }
    <div id="banner"></div>