I want that my background image stretch and scale depending on the browser viewport size.
I\'ve seen some questions on Stack Overflow that do the job, like
background-size: 100% 100%;
stretches the background to fill the entire element on both axes.
CSS3 has a nice little attribute called background-size:cover
.
This scales the image so that the background area is completely covered by the background image while maintaining the aspect ratio. The entire area will be covered. However, part of the image may not be visible if the width/height of the resized image is too great.
If you want to have the content centered horizontally, use a combination like this:
background-repeat: no-repeat;
background-size: cover;
background-position: center;
This will look beautiful.
Do you want to achieve this just using one image? Because you can actually make somewhat similar to a stretching background using two images. PNG images for instance.
I've done this before, and it's not that hard. Besides, I think stretching would just harm the quality of the background. And if you add a huge image it would slow down slow computers and browsers.
You can use the border-image : yourimage
property to scale the image up to the border. Even if you give the background-image, the border image will be drawn over it.
The border-image
property is very useful if your style sheet is implemented somewhere which doesn't support CSS 3. If you are using Google Chrome or Firefox, then I recommend the background-size:cover
property itself.
I wanted to center and scale a background image, without stretching it to the entire page, and I wanted the aspect ratio to be maintained. This worked for me, thanks to the variations suggested in other answers:
INLINE IMAGE: ------------------------
<div id="background">
<img src="img.jpg" class="stretch" alt="" />
</div>
CSS ----------------------------------
html {
height:100%;
}
#background {
text-align: center;
width: 100%;
height: 100%;
position: fixed;
left: 0px;
top: 0px;
z-index: -1;
}
.stretch {
margin: auto;
height:100%;
}