2013-06-20 152 views
2

當高度爲父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)

在此先感謝:-)

+0

的Javascript,我的朋友。 –

回答

0
$(document).ready(function() 
{ 
    $(window).resize(function() 
    { 
     $("div").height($("div").width()); 
    }); 
    $(window).resize(); 
}); 

您可以使用jQuery來匹配元素的高度和寬度做這樣的事情。

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

只需拖動'result'框架並觀看高度與框架寬度爲100%的寬度相匹配。 –

0

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