最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Resize DIV but maintain aspect ratio when window is resized - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Apr 8, 2012 at 3:11 JoeyJoey 11k17 gold badges42 silver badges56 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

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

http://jsfiddle/536UJ/

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';
}

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.

发布评论

评论列表(0)

  1. 暂无评论