Search code examples
cssbackground-image

How to keep same background-image ratio/size on all different screen sizes?


How do you keep the background-image same ratio so that it looks fitted for all different screen-sizes? In other words, how can I make sure the background-image always looks perfectly "centered". Please take note I have several other screens with other background-images so the solution should work for different images, not just the houses below.

CSS :

#background{
     background-image: url("../images/houses.png");
     background-color: whitesmoke; /* Used if the image is unavailable */
     height: 100%; /* You must set a specified height */
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover; /* Resize the background image to cover the entire container */
     text-align: center;
     padding: 2.5%;

}

This is the desired output for ALL screen sizes. Perfectly aligned : enter image description here

However when I resize and experiment with different sizes, the background gets misplaced and does not look really good. It looks like the image is a bit more to the right :

enter image description here


Solution

  • try this :

    #background{
      background-image: url("../images/houses.png"); /* The image used */
      background-color: whitesmoke; /* Used if the image is unavailable */
      height: 500px; /* You must set a specified height */
      background-position: center; /* Center the image */
      background-repeat: no-repeat; /* Do not repeat the image */
      background-size: cover; /* Resize the background image to cover the entire container*/
    }