width equal to dynamic height square [duplicate]

限于喜欢 提交于 2019-12-10 18:49:07

问题


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 :-)


回答1:


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



回答2:


$(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.




回答3:


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



来源:https://stackoverflow.com/questions/17211335/width-equal-to-dynamic-height-square

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!