How can I scale a div to fit inside the browser view port but preserve the aspect ratio of the div. How can I do this using CSS and/or JQuery?
Thanks!
How can I scale a div to fit inside the browser view port but preserve the aspect ratio of the div. How can I do this using CSS and/or JQuery?
Thanks!
This is possible with JQuery and a bit of maths.
Use JQuery to get the view ports width and height as well as the divs current dimensions.
$(document).width();
Calculate the divs current aspect ratio. eg width/height
You need a bit of logic to determine whether to set the width or height first, then use the initial ratio to calculate the other side.
jQuery has a plugin that grows an object until one of it's sides reaches a certain px-value. Coupling this will the viewport's height, you could expand any element to that size: jQuery MaxSide.
I got the code from http://css-tricks.com/maxside-jquery-plugin-and-how-to/, and I can get it to work on images, but for the life of me can't get it to work for the size of a div. Anything I may be missing?
There are a lot of ways to do this. I just slapped this together for a start.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<style type="text/css">
body{height:100%;background-color:#eee}
div{position:absolute;top:25%;bottom:25%;left:25%;right:25%;border:1px solid}
</style>
</head>
<body>
<div></div>
</body>
</html>
Rob, thanks for the response, but that wouldn't keep it's proportions; it would only keep it centered. If the browser window is dragged from a rectangle to a square, the div within will also become a square, which is what we're trying to avoid.