Background image responsive to mobile view using pure css

Issue

I want my background image to be responsive in mobile view.

I used this to scale my background image to the whole desktop:

 html  {
   background:url("image/2.jpg") no-repeat center center fixed;
   background-size: cover;
 }

But I cant have a great result in this: (this is most requested suggestion in my search)

@media only screen and (max-width: 600px) {
  html{
    width: 100%;
  }
} 

This is a desktop background img

While this is what happens in my mobile view img

Solution

One elegant solution would be to better controlling exactly what you want to show in landscape and portrait mode. If you want to be responsive with a landscape image on a portrait screen you necessarily have to "lose something", as per @salff comment

My snippet for being more flexible depending on user screen:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>


html
{
    background:url("https://www.hotelmedici.com/images/slide_home/11_Fori_imperiali_1600X917.jpg") no-repeat center center fixed;
    background-size: cover;
    width: 100%;
}

#warning-message { display: none; }

@media only screen and (orientation:portrait)
{
    #wrapper { display:none; }
    #warning-message { display:block; color: white;}
    
    html
    {
        background:url("https://s3files.core77.com/blog/images/2013/11/ESB-HalloweenLightShow-1.jpg") no-repeat center center fixed;
        background-size: cover;
        height: 100%;
    }       
}


</style>
</head>
<body>

<div id="wrapper">
    <h2>Responsive Images</h2>
    <p>If you want the image to scale both up and down on responsiveness, set the CSS width property to 100% and height to auto.</p>
    <p>Resize the browser window to see the effect.</p>
</div>

<div id="warning-message">
    this website is only viewable in landscape mode
</div>

</body>
</html>

NOTE: the code was produced crossing and tweaking your code, w3schools snippet and this answer

Answered By – Antonino

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published