I need a simple jquery solution to add a background image to my page filling it entirely, but keeping the aspect ratio and vertical and horizontal centered position.
there are several plugins out here but I don't want to use any plugin.
thanks in advance.
This code will do what you want..
$(function(){
var stretcher = $('#background-container > img'),
element = stretcher[0],
currentSize = { width: 0, height: 0 },
$document = $(document);
$(window).resize(function () {
var w = $document.width();
var h = $document.height();
if (currentSize.width != w || currentSize.height != h) {
stretcher.width(w).height('auto');
if (h > element.height) {
stretcher.width('auto').height(h);
}
currentSize.width = w;
currentSize.height = element.width;
}
})
$(window).load(function () {
$(this).trigger('resize');
});
});
Set your HTML like this
<div id="page">
Your page contents here..
</div>
<div id="background-container">
<img src="path/to/image" />
</div>
and your CSS like
#background-container{
position:absolute;
z-index:1;
top:0;
left:0;
width:100%;
height:100%;
overflow:hidden;
}
#page{
position:relative;
z-index:5;
}
Demo at http://jsfiddle.net/gaby/3YLQf/
Or you could use the CSS property :
background-size: cover
This will scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area.
You can control how your image is aligned within the viewport by using the background-position
property
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With