Reputation: 1473
I want an image to be 100% the width of the window minus the height of a header and its margin. At the same time, it should be no wider than the width of the window. This, I think I have achieved with the following code:
HTML:
<header></header>
<img id="photo" src="http://farm5.staticflickr.com/4031/4718599034_5ab720d0f9_b.jpg" realwidth="1024" realheight="768" />
CSS:
header {
position:absolute;
top:0px;
left:0px;
width:300px;
height:150px;
background-color:#000;
margin:20px;
}
img {
position:absolute;
bottom:10px;
left:0px;
max-width:1024px;
max-height:768px;
margin-right:20px;
margin-left:20px;
}
And, jQuery:
function setSize () {
var windowHeight = $(window).height();
var headerHeight = $('header').height();
var windowWidth = $(window).width();
$('img').height(windowHeight - headerHeight - 40);
$('img').width(windowWidth - 40);
}
$(window).resize(function () {
setSize();
setRatio();
});
setSize();
What I can't do and what I want to do is maintain the aspect ratio of the image. How might this be done?
Upvotes: 0
Views: 3663
Reputation: 114447
If you change the image's NATIVE height attribute, instead of its CSS height, the width will automatically follow the aspect ratio.
$('img').attr('height',(windowHeight - headerHeight - 40)+'px');
Upvotes: 1