2012-10-29 95 views
4

當一個元素在相對定位的元素中浮動時,如何使高度填充父元素? 浮動右側並填充父項

<div id="page"> 
    <div id="left"></div> 
    <div id="right"></div> 
</div> 
#page { 
    width: 980px; 
    padding: 10px; 
    background: #3C4B76; 
    display: block; 
    margin: 10px auto auto auto; 
    position: relative; 
} 

#left { 
    padding: 0; 
    margin: 0; 
    width: 230px; 
    float: left; 
} 

#right { 
    float: right; 
    width: 720px; 
    border-left: 1px solid white; 
    padding: 5px 5px 5px 20px; 
    height: 100%; 
    position: relative; 
    display: block; 
} 

在這個例子中#right元素不補「#page」元素,它只是長到那麼大的內容。如果它小於#page我想要#right填充父項。

+2

我已經更新了代碼的問題。 – Chud37

+0

'height:100%''需要適用於所有祖先直到'html'才能正常工作 –

+2

你的#頁面沒有指定高度。這意味着你從#right 100%的高度沒有影響。你有兩種可能性,你可以爲#page指定一個高度,爲#right指定一個最小高度,或者你使用javascript來找出#page的動態高度,然後設置#right的高度 –

回答

0

只要給它與父級相同的高度,並將一個clearfix應用到父級。

.clearfix:after { 
    visibility: hidden; 
    display: block; 
    font-size: 0; 
    content: " "; 
    clear: both; 
    height: 0; 
    } 
.clearfix { display: inline-block; } 
/* start commented backslash hack \*/ 
* html .clearfix { height: 1%; } 
.clearfix { display: block; } 
/* close commented backslash hack */ 
+1

以及我一直使用明確:都在DIV定位在woodwood之後,但是如果#left比#right大,那麼無論我嘗試什麼,#right都不會填充該元素。 – Chud37

1

複製粘貼以下

CSS:

#page { 
    width: 980px; 
    padding: 10px; 
    background: #3C4B76; 
    display: block; 
    margin: 10px auto auto auto; 
    position: relative; 
} 

#left { 
    padding: 5px 0; 
    margin: 0; width: 230px; 
    float: left; 
} 

#right { 
    float: right; 
    width: 720px; 
    border-left: 1px solid white; 
    padding: 5px 5px 5px 20px; 
    height: 100%; 
    position: relative; 
    display: block; 
} 

.clearfix:after { 
    visibility: hidden; 
    display: block; 
    font-size: 0; 
    content: " "; 
    clear: both; 
    height: 0; 
    } 
.clearfix { display: inline-block; } 
/* start commented backslash hack \*/ 
* html .clearfix { height: 1%; } 
.clearfix { display: block; } 
/* close commented backslash hack */ 

HTML:

<div id="page" class="clearfix"> 
    <div id="left">left</div> 
    <div id="right">right</div> 
</div> 

小提琴鏈接:

http://jsfiddle.net/uExdD/9/

5

試試這個父:

overflow:auto; 

另一種解決方案:

父:

display: table; 

孩子:

display: table-row; 

選中此fiddle

UPDATE: 要設置跨瀏覽器CSS等高列,你應該閱讀本Matthew James post

+0

沒關係,但左邊比右邊長的時候怎麼樣:http://jsfiddle.net/j7wd4/1/ – Chud37

+0

@ Chud37我明白了你的觀點,檢查更新 –