Jon
Jon

Reputation: 8511

Background Image Stretch 100% Height of Div

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>

Upvotes: 19

Views: 63877

Answers (4)

Nizam Kazi
Nizam Kazi

Reputation: 1920

In case background-size: contain; is not helpful and if you are looking for full HEIGHT background image without loosing aspect ratio then use below written CSS

background-size: auto 100%;

setting first parameter to "auto" will ensure that image keep width in ratio of current height. Second parameter which is "100%" will help background image adapt same height as DIV.

Upvotes: 19

defau1t
defau1t

Reputation: 10619

There is a property in css3 called as background-size:cover; and background-size:contain;. You might want to use background-size:cover; to suit your needs.

**contain

Specifies that the background image should be scaled to be as large as possible while ensuring both its dimensions are less than or equal to the corresponding dimensions of the background positioning area.



cover

Specifies that the background image should be scaled to be as small as possible while ensuring both its dimensions are greater than or equal to the corresponding dimensions of the background positioning area.

**

Upvotes: 3

Henrik
Henrik

Reputation: 4034

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.

Upvotes: 47

gregory
gregory

Reputation: 1140

Did you try background-size: cover; ?

In your example you're adjusting background-position.

Upvotes: 4

Related Questions