CSS background image - shrink to fit fixed size div
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_compatibilityIf 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 syntaxbackground: <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;
}
you should use:
.container{
background-size: 100%;
}