2

I want to add a cover image to my web site. I have a div tag in the top of the page. I have set the div tag's width to 80% and height to auto. I want add an image as the background of that div. That image width should stretch according to the width of the div. Image height should changed automatically according it's new width (stretched width).

5 Answers5

3
.style1 {
        background: url(images/bg.jpg) no-repeat center center fixed;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
}

why wont you just use patterns instead of crippling web?

bazinga
  • 881
  • 2
  • 7
  • 13
1

You can use the CSS3 background-size property.

http://jsfiddle.net/9UNVT/

CSS

.background { border:1px solid red; width:500px; height:500px; background:url('http://placehold.it/100x100') 0 0 no-repeat; }
.cover { background-size:cover; }

HTML

<div class="background">
    no-cover
</div>

<div class="background cover">
    cover
</div>

Note : I have just used background-size, but you'll probably need to include all the vendor prefixed versions if you want to make it more flexible.

Nick R
  • 7,704
  • 2
  • 22
  • 32
  • Consider using `background-size: 100% auto` if it should stretch only to fill the width. `background-size: cover` stretches the image to fill the height as well. – Henrik Oct 31 '13 at 12:34
  • Naa, both will preserve aspect-ratio. You're thinking of `background-size: 100% 100%`, which will break aspect-ratio to fill the element. – Henrik Oct 31 '13 at 15:36
  • Ah yes of course, since we use `max-width:100%` and `height:auto;` for scalable images. – Nick R Oct 31 '13 at 15:40
1

you better to try this code.. background image will stretch depending on the width.

<div class="container">
</div>


.container {
width:80%;
background:url(image.png) no-repeat center center;
background-size:100% 100%;
}
vadlamani
  • 137
  • 2
  • 2
  • 10
0
.style1 {
        background: url(images/bg.jpg) center center;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
-ms-background-size: cover;
        background-size: cover;
}
.style1 {
background-size:100% 100%
}
Bipin Kumar Pal
  • 1,009
  • 2
  • 8
  • 16
-1

You can always set image as a background image:

.div {

background-image:url('image.jpg');

}
Dr Robotnik
  • 352
  • 1
  • 4
  • 14