pistacchio
pistacchio

Reputation: 58863

Stretching image

I have a wrapper div that contains arbitrary content (I don't know its length). How can I put a background image that stretches its whole length since background-images doesn't stretch?

I've tried with a div containing a img tag. The div has a lover z-index that the rest of the content and has position: absolute. The problem is that the image is longer that the content and so it just makes it longer (the wrapper has overflow: auto).

<div id="wrapper">
    <div id="image-wrapper" style="position: absolute"><img src="bg.jpg"></div>
    [.. OTHER CONTENT ..]
</div>

If I set the div and the image's width and height to 100%, it takes the window's height, not the wrapper's.

Any help?

Upvotes: 4

Views: 166

Answers (4)

Blazemonger
Blazemonger

Reputation: 92893

Add position: relative to the styles for #wrapper.

http://css-tricks.com/absolute-positioning-inside-relative-positioning/

Upvotes: 0

vonsko
vonsko

Reputation: 395

you might also try html5 method on image.

#image-wrapper img {max-width: 100%}

Upvotes: 0

Alp
Alp

Reputation: 29739

background-size is available since CSS3:

#image {
  background-image: url("bg.png");
  background-size: auto;
}

auto is the default value and does not stretch the image.

You can set the width and height manually:

#image {
  background-size: 100% 100%;
}

or

#image {
  background-size: 500px 300px;
}

The alternative: background-size: contain and background-size: cover.

contain stretches the image so that the image is as big as possible but completely visible within the element, whereas cover stretches the image to 100% width, regardless if the image is cropped at the top and/or the bottom.

But the different browsers are not completely consistent when rendering backgrounds with these keywords.

Upvotes: 6

If you are willing to use JavaScript, check out Supersized. It seems to work well for this particular case.

Upvotes: 1

Related Questions