Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background Image Stretch 100% Height of Div

Tags:

html

css

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>
like image 356
Jon Avatar asked Nov 23 '12 19:11

Jon


People also ask

Can you stretch background image?

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.

How do I stretch a div image?

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.

How do I stretch a background image to fit?

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.

How do you make a background image full height in CSS?

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.


1 Answers

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.

like image 111
Henrik Avatar answered Oct 14 '22 08:10

Henrik