33

I have a <div> with a background Image.

The <div> size may change over the time.

Is it possible setting the Divs Background image to fit the <div> size?

Lets say I have a div which is 400x400 and an Image which is 1000x1000, is it possible to shrink the image to 400x400 and therefore fit the <div> size?

Cody Guldner
  • 2,882
  • 1
  • 22
  • 36
kfirba
  • 4,773
  • 13
  • 38
  • 68

9 Answers9

63

If you'd like to use CSS3, you can do it pretty simply using background-size, like so:

background-size: 100%;

It is supported by all major browsers (including IE9+). If you'd like to get it working in IE8 and before, check out the answers to this question.

Community
  • 1
  • 1
dsgriffin
  • 64,660
  • 17
  • 133
  • 135
26

Use background-size for that purpose:

background-size: 100% 100%;

More on:

http://www.w3schools.com/cssref/css3_pr_background-size.asp

17

Use background-size property to achieve that. You should choose between cover, contain and 100% - depending on what exactly you'd like to get.

MarcinJuraszek
  • 121,297
  • 15
  • 183
  • 252
7

You can achieve this with the background-size property, which is now supported by most browsers.

To scale the background image to fit inside the div:

background-size: contain;

To scale the background image to cover the whole div:

background-size: cover;
Prajwal
  • 281
  • 4
  • 10
2

Use this as it can also act as responsive. :

background-size: cover;
Sankalp Singha
  • 4,361
  • 5
  • 37
  • 57
1

You could use the CSS3 background-size property for this.

.header .logo {
background-size: 100%;
}
Haresh Shyara
  • 1,578
  • 9
  • 13
0

Set your css to this

img {
    max-width:100%,
    max-height100%
}
miguel.gazela
  • 133
  • 2
  • 14
0

Wanted to add a solution for IE8 and below (as low as IE5.5 I think), which cannot use background-size

div{
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=
'/path/to/img.jpg', sizingMethod='scale');
}
chiliNUT
  • 17,890
  • 12
  • 63
  • 99
0

This should work but will not keep the image aspect ratio:

 background-size: 100% 100%;