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


Use width: 50% in css and window.onresize to resize. Take a look



http://jsfiddle.net/536UJ/

+6


source


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


You can set the width to 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';
}

      

+1


source







All Articles