3

Is it possible with either css or js to set the width of an element to match it's height when the height is a % of the parent div. The child div also needs to change size if browser window is resized.

Example

body, html {height: 100%}
.parent {height: 100%; width: 960px;}
.child {
    height: 50%; 
    width: same as height; /* but not 50% of 960px, so that the child div is square*/
}

I'm trying to achieve something like this but width rather than height. Height equal to dynamic width (CSS fluid layout)

Thanks in advance :-)

Community
  • 1
  • 1
rosie607
  • 31
  • 1
  • 2

3 Answers3

0

If you are using jQuery, you can set the width = height or vice-versa in the resize() function.

http://jsfiddle.net/Ev6Vj/173/

$(window).resize(function() {
  $('#main').height($('#main').width());
});
<div id="main">
    <img src="http://placehold.it/200x200" />
</div>
#main {
    position: absolute;
    bottom: 0;
    top: 0;
    border: #000 thin solid;
    background: #DDEEFF;
    width: 100%;
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
-1
$(document).ready(function()
{
    $(window).resize(function()
    {
        $("div").height($("div").width());
    });
    $(window).resize();
});

You can do something like this using jQuery to match the height and width of an element.

Siddharth Nagar
  • 392
  • 2
  • 13
-1

Use jquery.

function resizeChild() {
var child = $(".child");
var parentSize = child.parent().height();
child.height(parentSize / 2);
child.width(parentSize / 2);
}
$(window).ready(resizeChild);
$(window).resize(resizeChild);

see fiddle

raam86
  • 6,785
  • 2
  • 31
  • 46