CSS background image - shrink to fit fixed size div

user1187968 picture user1187968 · Sep 18, 2016 · Viewed 57.5k times · Source

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.

Answer

henry picture henry · Sep 18, 2016

You're looking for background-size: contain (see the MDN 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>

Notes:

  • These days you almost certainly don't need the browser prefixes, meaning you can just use background-size: contain. See https://developer.mozilla.org/en-US/docs/Web/CSS/background-size#Browser_compatibility

  • If you're using Autoprefixer (included in many build tools and build setups) it will automatically add any necessary prefixed versions for you, meaning you could do background-size: contain even if current versions of the major browsers still required prefixes.

  • You can include size in the background shorthand property with the syntax background: <background-position>/<background-size>. That would look like

.container{
    background: url(https://s21.postimg.org/iq2mtjaiv/bg_boardwalk.jpg) no-repeat center/contain;

    height: 150px;
    width: 300px;
}