2012-01-04 127 views
1

如果我有一個位於left: 5000pxdiv#child,並且我的窗口比這個窄,那麼我的div#parent可能足夠寬以容納它的孩子嗎?使元素足夠寬以包含絕對定位的元素

A width: 100%只與身體一樣寬,不包含孩子。我不知道孩子的寬度/位置。我不想使用JavaScript(但是如果我必須,如何?)。

回答

1

絕對定位的元素不再是佈局的一部分。父母不知道孩子有多大。是的,您需要使用JavaScript根據孩子的大小和位置調整父母的寬度。

上級寬度= childWith + childLeft

+0

感謝您的解釋。 – 2012-01-05 00:11:39

1

我認爲你應該使用JavaScript/jQuery的爲你的目標。以下是在jQuery的樣品溶液:http://jsfiddle.net/hU2TV/

CSS

#parent { 
    width: 100%; 
    background-color: red; 
    height: 100px; 
} 
#child { 
    position: absolute; 
    left: 700px; 
    background-color:blue; 
    width: 50px; 
    height: 50px; 
} 

JS

(function ($) { 
    var child = $('#child'), parent = $('#parent'); 
    if (child.offset().left + child.width() > parent.width()) { 
     parent.width(child.offset().left + child.width()); 
    } 
}($)); 

HTML

<div id="parent"><div id="child"></div></div> 

此致敬意!