Joey
Joey

Reputation: 10965

Resize DIV but maintain aspect ratio when window is resized

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

Answers (3)

manojadams
manojadams

Reputation: 2430

Use width:50% in css and window.onresize event for resize. Have a look

http://jsfiddle.net/536UJ/

Upvotes: 7

Imp
Imp

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

kennebec
kennebec

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

Related Questions