89

Below css sets an individual background on two divs; the images repeat themselves if they do not fit into the div size.

How can I stretch the images using css to fit into space required by div ?

<style type="text/css">   
#contentMain {  
  margin-bottom: 5%; 
  margin-top: 10%;
  margin-left: 10%;
  margin-right: 10%;
  background: url( /jQuery/mypage/img/background1.png )
}  
#page1 {    
  background: url( /jQuery/mypage/img/background2.png )  
} 
</style> 
whostolemyhat
  • 3,107
  • 4
  • 34
  • 50
user701254
  • 3,935
  • 7
  • 42
  • 53

3 Answers3

231

Answer

You have multiple options:

  1. background-size: 100% 100%; - image gets stretched (aspect ratio may be preserved, depending on browser)
  2. background-size: contain; - image is stretched without cutting it while preserving aspect ratio
  3. background-size: cover; - image is completely covering the element while preserving aspect ratio (image can be cut off)

/edit: And now, there is even more: https://alligator.io/css/cropping-images-object-fit

Demo on Codepen

Update 2017: Preview

Here are screenshots for some browsers to show their differences.

Chrome

preview background types chrome


Firefox

preview background types firefox


Edge

preview background types edge


IE11

preview background types ie11

Takeaway Message

background-size: 100% 100%; produces the least predictable result.

Resources

Alp
  • 29,274
  • 27
  • 120
  • 198
  • 2
    See http://www.css3.info/preview/background-size/ and the more theoretical http://www.w3.org/TR/css3-background/#the-background-size – jao May 17 '11 at 09:31
  • 1
    thank you, @Alp and @jao! this answer and comment really helped me instead of using ugly javascript to create a separate img element and then set the height and width before putting the img back into the div instead. – Kim Stacks Sep 28 '12 at 04:41
10

i would recommend using this:

  background-repeat:no-repeat;
  background-image: url(your file location here);
  background-size:cover;(will only work with css3)

hope it helps :D

And if this doesnt support your needs just say it: i can make a jquery for multibrowser support.

Bram B
  • 368
  • 2
  • 14
4

With the background-size property in those browsers which support this very new feature of CSS.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335