Reputation: 11
I know there's some plugins about for scaling a background image for a webpage, but this is a bit different.
I'm trying to get a div to resize proportionally, and have the background image inside also resize proportionally. It works for resizing horizontally.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<style type="text/css" media="screen">
body {
background: #000;
overflow-x: hidden;
overflow-y: hidden;
}
#bg
{
z-index: -1;
position: absolute;
top:0;
left:0;
}
#wrap
{
position: relative;
margin: 0 auto;
}
</style>
</head>
<body>
<div id="wrap">
<img src="bg.jpg" id="bg" width="100%" />
hi
</div>
<script type="text/javascript" charset="utf-8" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>
<script type="text/javascript" charset="utf-8">
var minWidth = 400;
var minHeight = 400;
var maxWidth = 500;
var maxHeight = 500;
function resize() {
var windowWidth = $(window).width();
var windowHeight = $(window).height();
var w = windowWidth < minWidth ? minWidth :
windowWidth > minWidth && windowWidth < maxWidth ? windowWidth :
windowWidth > maxWidth ? maxWidth :
minWidth;
var h = windowHeight < minHeight ? minHeight :
windowHeight > minHeight && windowHeight < maxHeight ? windowHeight :
windowHeight > maxHeight ? maxHeight :
minHeight;
$("#wrap").css({
'width': w + 'px',
'height': h + 'px'
});
}
$(document).ready(function() {
resize();
$(window).resize(function() {
resize();
});
});
</script>
</body>
</html>
Upvotes: 1
Views: 1769
Reputation: 66389
Instead of using real background you can use ordinary <img>
tag and emulate background by using absolute positioning.. proof of concept: http://jsfiddle.net/yahavbr/vu4Zh/
HTML code:
<div id="ImageContainer">
<img class="background" src="mybackground.gif" border="0" />
<div class="contents">
Hello World
</div>
</div>
CSS:
#ImageContainer { width: 300px; position: relative; }
#ImageContainer .background { width: 100%; position: absolute; left: 0px; top: 0px; z-index: 1; }
#ImageContainer .contents { position: absolute; left: 0px; top: 0px; z-index: 99; }
By having this the image will automatically scale itself to its container, no script involved.
Upvotes: 1
Reputation: 14856
You are stretching the div where the image is within (which is working properly). But the image has no percental height given and therefore it is not affected when the parent DIV is resized.
Upvotes: 0