Resize the DIV, but keep the aspect ratio when the window is resized
I have a DIV element on my page that I want to resize when the window is resized, but maintain a square aspect ratio. I want the width to be 50% of the browser width and the height to be equal to the width. How can i do this?
If the solution requires Javascript, that's fine, but I'd rather not use jQuery.
+3
source to share
3 answers
I'm not sure if you can make one property (height) equal to another property (width) in CSS ... well, at least in CSS 2.
But you can of course do it in JavaScript.
<div id = "myDiv"></div>
<script>
document.onresize = function() {
var element = document.getElementById('myDiv'); // the element
var size = Math.floor(window.innerWidth / 2) + 'px'; // 50% window width
element.style.width = size; // set the width
element.style.height = size; // set the height
};
</script>
Note that the property is window.innerWidth
missing in IE. There you will need to use document.documentElement.clientWidth
.
+1
source to share