Reputation: 10965
I have a DIV element in my page, that I want to resize when the window is resized, but maintain a square aspect ratio. I want to set 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 prefer not to use jQuery.
Upvotes: 3
Views: 4914
Reputation: 2430
Use width:50%
in css and window.onresize
event for resize. Have a look
Upvotes: 7
Reputation: 8609
I'm not sure you can make one property (height) equal to other property (width) in CSS... well, at least in CSS 2.
But you of course can do this 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 window.innerWidth
property is not present in IE. There, you'll have to use document.documentElement.clientWidth
.
Upvotes: 1
Reputation: 104760
You can set the width to be 50% of the window in css; you just need to adjust the height-
window.onresize=function(){
var who= document.getElementById('divtoresize');
who.style.height=who.offsetWidth+'px';
}
Upvotes: 1