user1187968 user1187968 - 2 months ago 16
CSS Question

CSS background image - shrink to fit fixed size div

I have the following code at https://jsfiddle.net/ncrcfduz, and a background image at https://s21.postimg.org/iq2mtjaiv/bg_boardwalk.jpg. I need to make the background image rescale to fit in the div, preferred to show most of the "centered" content in the image. The following code only show the top-left corner of the image.

<div class="container">
</div>

.container{
background: url(https://s21.postimg.org/iq2mtjaiv/bg_boardwalk.jpg) no-repeat fixed;
-webkit-background-size: cover;
-moz-background-size : cover;
-o-background-size: cover;
background-size: cover;

height: 150px;
width: 300px;
}


https://jsfiddle.net/ncrcfduz/

Answer

You're looking for background-size: contain (see the css-tricks' entry), not cover. To get your example to work, you'll have to drop the background-attachment: fixed. Use background-position: center to center the background in your div.

.container{
    background: url(https://s21.postimg.org/iq2mtjaiv/bg_boardwalk.jpg) no-repeat center;
    -webkit-background-size: contain;
    -moz-background-size: contain;
    -o-background-size: contain;
    background-size: contain;
    
    height: 150px;
    width: 300px;
}
<div class="container">
</div>

Comments