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>
Answer
You have multiple options:
background-size: 100% 100%;– image gets stretched (aspect ratio may be preserved, depending on browser)background-size: contain;– image is stretched without cutting it while preserving aspect ratiobackground-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
Firefox
Edge
IE11
Takeaway Message
background-size: 100% 100%;produces the least predictable result.Resources