Resize Background image with Jquery
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/jquery.dimensions.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var $winwidth = $(window).width();
$("img.source-image").attr({
width: $winwidth
});
$(window).bind("resize", function(){
var $winwidth = $(window).width();
$("img.source-image").attr({
width: $winwidth
});
});
});
</script>
In order to get this inline image to behave more like a background image, we can use that unique class we applied to apply some absolute positioning.
img.source-image {
position: absolute;
top: 0;
left: 0;
}
Because of this absolute positioning, anything that you want to put over it will also need positioning and a higher z-index value. If your source image is particularly tall, or your browser window is particularly wide, the image could easily become taller than your browser window and force a vertical scrollbar. In order to prevent this, simply set the overflow value on your body to hidden:
body {
overflow: hidden;
}
Or Just css
Forget this javascript business! Thanks to Anders comment pointing out Stu Nicholls version, here is an even better way to handle this without the need for any javascript at all!
Since we already have a unique class on the image, the image is absolutely positioned, and the scrollbars thing is already taken care of, let’s just set the width using a percentage directly in the CSS:
#img.source-image {
width: 100%;
position: absolute;
top: 0;
left: 0;
}
This entry was posted on Friday, February 27th, 2009 at 8:04 pm and is filed under css, tutorial. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.


