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,888
  • 1
  • 25
  • 36
kfirba
  • 5,231
  • 14
  • 41
  • 70

9 Answers9

64

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
  • 66,495
  • 17
  • 137
  • 137
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
  • 124,003
  • 15
  • 196
  • 263
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
  • 319
  • 4
  • 10
2

Use this as it can also act as responsive. :

background-size: cover;
Sankalp Singha
  • 4,461
  • 5
  • 39
  • 58
1

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

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

Set your css to this

img {
    max-width:100%,
    max-height100%
}
miguel.gazela
  • 143
  • 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
  • 18,989
  • 14
  • 66
  • 106
0

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

 background-size: 100% 100%;
Sharhabeel Hamdan
  • 1,273
  • 13
  • 15