I have a container that will grow/shrink in height based on how much text is dynamically placed inside it. The container will have a background image that needs to stretch/shrink as the container changes height and this image cannot be cropped in any way. I am wondering how would I style .container
to get the background-image to be stay 100% of the div.
I have tried the following, but it didn't seem to work:
.container { background: url('backgroundImage.jpg') 0 100% no-repeat; }
Sample of HTML Structure:
<div class="container">
<p class="text">This is a short container</p>
</div>
<div class="container">
<p class="text">This<br> is<br> a<br> tall<br> container</p>
</div>
You can use the CSS background-size: cover; to stretch and scale an image in the background with CSS only. This scales the image as large as possible in such a way that the background area is completely covered by the background image, while preserving its intrinsic aspect ratio.
Answer: Use the CSS max-width Property You can simply use the CSS max-width property to auto-resize a large image so that it can fit into a smaller width <div> container while maintaining its aspect ratio.
When you work with background images, you may want an image to stretch to fit the page despite the wide range of devices and screen sizes. The best way to stretch an image to fit the background of an element is to use the CSS3 property, for background-size, and set it equal to cover.
CSS-Only Technique #1 We set a min-height which keeps it filling the browser window vertically, and set a 100% width which keeps it filling horizontally. We also set a min-width of the width of the image so that the image never gets smaller than it actually is.
You need to set the background-size
property.
background-size: 100% 100%;
will scale it to fill the container both horizontally and vertically.
I usually prefer background-size: cover;
as it gracefully scales up the image as needed, maintaining the aspect ratio. Make sure to check the support for background-size, as it is a fairly new property.
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