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.
.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; }
<div class="container"> </div>
The background-size CSS property lets you resize the background image of an element, overriding the default behavior of tiling the image at its full size by specifying the width and/or height of the image.
To auto-resize an image or a video to fit in a div container use object-fit property. It is used to specify how an image or video fits in the container. object-fit property: This property is used to specify how an image or video resize and fit the container.
Use: background-size: 100% 100%; To make background image to fit the div size.
How to fit image without stretching and maintain aspect ratio? Answer: If you want to use the image as a CSS background, there is an elegant solution. Simply use cover or contain in the background-size CSS3 property. contain will give you a scaled-down image.
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>
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; }
you should use:
.container{ background-size: 100%; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With