2014-02-14 36 views
6

我目前的問題是我有三個div元素;一個向左漂移,一個向右漂移,另一個在兩個之間漂移。我希望中心div自動拉伸到兩個div之間可用寬度的最大寬度。如何在兩個div之間製作div的寬度

HTML

<div id="contain"> 
    <div id="left">1</div> 
    <div id="filler"></div> 
    <div id="right">2</div> 
</div> 

CSS

#left { 
    text-decoration: none; 
    display: inline-block; 
    float: left; 
    width: auto; 
    padding: 0px 20px 0px 20px; 
    height: 45px; 
    text-align: center; 
    line-height: 300%; 
    background: #FF9000; 
    color: #FFFFFF; 
} 
#navFiller { 
    display: inline-block; 
    position: fixed; 
    float: left; 
    width: auto; 
    height: 45px; 
    background: #FF9000; 
} 
#right { 
    text-decoration: none; 
    display: inline-block; 
    float: right; 
    width: auto; 
    padding: 0px 20px 0px 20px; 
    height: 45px; 
    text-align: center; 
    line-height: 300%; 
    background: #FF9000; 
    color: #FFFFFF; 
} 
#contain { 
    width: 100%; 
    height: 45px; 
    padding: 0; 
    margin: 0; 
    display: inline; 
} 

的jsfiddle項目:

http://jsfiddle.net/msEBU/

+1

你應該這樣做與JavaScript而不是我認爲.. – Panda

回答

9

如果在浮動元素之後添加填充元素,然後改變了它的風格一點點(包括給出正確的樣式塊ID),你可以得到你要什麼:

#left { 
 
    display: inline-block; 
 
    float: left; 
 
    padding: 0px 20px 0px 20px; 
 
    height: 45px; 
 
    text-align: center; 
 
    line-height: 300%; 
 
    background: #FF9000; 
 
    color: #FFFFFF; 
 
} 
 
#filler { 
 
    display: block; 
 
    float: none; 
 
    height: 45px; 
 
    background: #F00; 
 
} 
 
#right { 
 
    display: inline-block; 
 
    float: right; 
 
    padding: 0px 20px 0px 20px; 
 
    height: 45px; 
 
    text-align: center; 
 
    line-height: 300%; 
 
    background: #FF9000; 
 
    color: #FFFFFF; 
 
} 
 
#contain { 
 
    width: 100%; 
 
    height: 45px; 
 
    padding: 0; 
 
    margin: 0; 
 
    display: inline; 
 
}
<div id="contain"> 
 
    <div id="left">1</div> 
 
    <div id="right">2</div> 
 
    <div id="filler">m</div> 
 
</div>


OR,模擬表:

#contain { 
 
    width: 100%; 
 
    padding: 0; 
 
    margin: 0; 
 
    display: table; 
 
} 
 
#left, 
 
#right { 
 
    text-decoration: none; 
 
    display: table-cell; 
 
    width: 5%; 
 
    text-align: center; 
 
    background: #FF9000; 
 
    color: #FFFFFF; 
 
    padding: 2% 0; 
 
} 
 
#filler { 
 
    display: table-cell; 
 
    width: auto; 
 
    background: #F00; 
 
}
<div id="contain"> 
 
    <div id="left">1</div> 
 
    <div id="filler">m</div> 
 
    <div id="right">2</div> 
 
</div>

兩種方法有他們的好處。這取決於你,這對你是對的。

+0

謝謝!我只是將其添加到我的項目中,它完美地工作! –

+0

你並不需要表格中的行元素:http://stackoverflow.com/questions/16120957/can-i-use-table-cell-as-a-stand-alone-style – cimmanon

+0

@cimmanon - 好的,謝謝。 – George

0

CSS的許多實現不支持不同浮動層之間的自動調整大小關係。儘管有很多解決方案。我的建議是使用一小部分的JavaScript。我用的jQuery以下行有一些小的CSS調整:

$('#filler').outerWidth($('#contain').width()-$('#right').outerWidth()-$('#left').outerWidth()); 

小提琴: http://jsfiddle.net/K9C4u/2/

另外請注意,我感動的div到同一行,因爲它使一個文本節點與空間爲每個返回+選項卡。