【问题标题】:width equal to dynamic height square [duplicate]宽度等于动态高度正方形[重复]
【发布时间】:2013-06-17 04:10:16
【问题描述】:

当高度是父 div 的百分比时,是否可以使用 css 或 js 设置元素的宽度以匹配它的高度。如果调整浏览器窗口的大小,子 div 也需要更改大小。

示例

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*/
}

我正在尝试实现这样的目标,但要实现宽度而不是高度。 Height equal to dynamic width (CSS fluid layout)

提前致谢:-)

【问题讨论】:

  • Javascript,我的朋友。

标签: javascript css dynamic height width


【解决方案1】:

如果您使用的是 jQuery,您可以在 resize() 函数中设置width = height 或反之亦然。

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

【讨论】:

  • 只需拖动result 框架并观察高度与100% 框架宽度的宽度匹配。
【解决方案2】:
$(document).ready(function()
{
    $(window).resize(function()
    {
        $("div").height($("div").width());
    });
    $(window).resize();
});

您可以使用 jQuery 来匹配元素的高度和宽度。

【讨论】:

    【解决方案3】:

    使用 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-23
      • 1970-01-01
      • 2014-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-11
      相关资源
      最近更新 更多