George Welder George Welder - 11 days ago 6
CSS Question

How to make full width image responsive? (no scale / stretch)

So I've learned about responsive design, and seems pretty straightforward. However, there is one thing I do not understand. I have a big fullwidth image in the center of my homepage. It has a certain size, and CSS seems to require the size in pixels - if I type in % it does not show.

So for now I have

.picture-main {
/*background-color: gray;*/
background-image: url("./images/homepage_main_picture.png");
background-repeat: no-repeat;

background-position: center;
background-size: cover;

padding-right: 0;
margin-right: 0;
padding-left: 0;
margin-left: 0;
width: 100%;
height: 250px;
}


However, if I change the size of my browser window in order to check responsiveness, it will just scale & stretch it accordingly and the image will be distorted, looking horrible. Does anybody have a solution?

PS: note that other answers here on stackoverflow do not address my question, or at least so I believe. e.g.this one here which is also entitled "how-to-make-a-full-width-image-responsive". - maybe I phrased my question wrongly then?

Answer

Try using background-size: contain; that way the background image will keep it's proportions.

.picture-main {
  background: url("//placehold.it/500x300/cf5") no-repeat 50%;
  padding: 0; margin: 0;
  width: 100%;
  height: 250px;
}

.contain{
  background-size: contain;
}
.cover{
  background-size: cover;
}
Example using background-size: contain
<div class="picture-main contain"></div>

Example using background-size: cover
<div class="picture-main cover"></div>

Comments