2011-04-01 99 views
47
<div id="parent" style="overflow:hidden; position:relative;"> 
    <div id="child" style="position:absolute;"> 
    </div> 
</div> 

我需要顯示大於它的父元素,但沒有刪除溢出的子元素:隱藏;這可能嗎? 父元素有position:relative; 子元素一旦離開它的父代邊界就會被剝離。絕對位置和溢出:隱藏

(元素都額外的CSS定義我只是把樣式屬性清晰度)

+1

看看[此鏈接](http://jsfiddle.net/ Town/uLeWp/2 /),這是你想要的嗎?這基本上是你已經在做的。 – Town 2011-04-01 12:46:35

+0

你有不好的示例代碼。這:''子元素一旦離開它的父母邊界就會被剝離「'不會出現在你當前的代碼中,請參閱:http://jsfiddle.net/thirtydot/wPPH5/添加一個更好的示例。 – thirtydot 2011-04-01 12:46:52

+0

除非您指定父母的身高以使其足夠大以適應孩子,否則不會。 「overflow:hidden」與你的要求相反。它是一個或另一個,而不是兩個。 – Bazzz 2011-04-01 12:47:01

回答

30

這是完全不可能做到你想要與父divoverflow: hiddenposition: relative什麼..相反,你可以引入額外的兒童div和移動overflow: hidden了這一點。

參見:http://jsfiddle.net/thirtydot/TFTnU/

HTML:

<div id="parent"> 
    <div id="hideOverflow"> 
     <div style="width:1000px;background:#ccc">sdfsd</div> 
    </div> 
    <div id="child">overflow "visible"</div> 
</div> 

CSS:

#parent { 
    position:relative; 
    background:red; 
    width:100px; 
    height:100px 
} 
#child { 
    position:absolute; 
    background:#f0f; 
    width:300px; 
    bottom: 0; 
    left: 0 
} 
#hideOverflow { 
    overflow: hidden 
} 
+2

請注意,如果您刪除位置:相對屬性,則子可能會溢出。 – Grsmto 2012-08-02 13:16:10

+0

這仍然抓住我。這也是一個明顯的解決方案。 – 2014-04-07 15:54:36

0

使用CSS ...

* {margin: 0; padding: 0;} 

#parent {width: auto; overflow: hidden;} 

#child {position: absolute; width: auto;} 

隨着寬自它將始終追加到儘可能小的尺寸;並重置它將有助於保持自然流動。

但是,如果孩子比父母更大,那麼這是不可能的。但是通過這個CSS,我認爲你會盡可能地達到你想要的最大值。

1

我通常使用溢出:隱藏的clearfix。在這種情況下,我放棄了,只是添加一個額外的div。

<div id="parent" style="position:relative;"> 
    <!-- floating divs here --> 
    <div id="child" style="position:absolute;"></div> 
    <div style="clear:both"></div> 
</div> 
3

下面的代碼就像一個魅力。

<div id="grandparent" style="position:relative;"> 
    <div id="parent" style="overflow:hidden;"> 
     <div id="child" style="position:absolute;"> 
     </div> 
    </div> 
</div> 
0

thirtydot的解決方案其實是一個好主意。

這裏有一個更清楚的例子:http://jsfiddle.net/y9dtL68d/

HTML

<div id="grandparent"> 
    <div id="parent"> 
     <p>this has a lot of content which ...</p> 
     <p>this has a lot of content which ...</p> 
     <p>this has a lot of content which ...</p> 
     <p>this has a lot of content which ...</p> 
     <p>this has a lot of content which ...</p> 
     <p>this has a lot of content which ...</p> 
     <p>this has a lot of content which ...</p> 
    </div> 
    <div id="child"> 
     dudes 
    </div>  
</div> 

CSS

#grandparent { 
    position: relative; 
    width: 150px; 
    height: 150px; 
    margin: 20px; 
    background: #d0d0d0; 
} 
#parent { 
    width: 150px; 
    height: 150px; 
    overflow:hidden; 
} 
#child { 
    position: absolute; 
    background: red; 
    color: white; 
    left: 100%; 
    top: 0; 
}