2014-12-18 84 views
0

我有以下HTML結構:div元素如何在CSS3 Flexbox中僅佔用其內部空間的空間?

<div class="indicator"></div> 
<div class="mainPanel"> 
    <div>Speichern</div> 
    <div>Style</div> 
    <div>Speichern</div> 
</div> 

mainPanel中包含三個元素。中間的元素應該始終處於中心如下所示:

enter image description here

這裏是CSS代碼我用

.indicator { 
    -webkit-box-sizing: border-box; 
    -moz-box-sizing: border-box; 
    box-sizing: border-box; 
    position: absolute; 
    width: 150px; 
    height: 50px; 
    border-right: 1px solid red; 
    z-index: -10; 
} 
.mainPanel { 
    width: 300px; 
    height: 50px; 
    -webkit-box-sizing: border-box; 
    -moz-box-sizing: border-box; 
    box-sizing: border-box; 
    display: -webkit-box; 
    display: -ms-flexbox; 
    display: -webkit-flex; 
    display: flex; 
    -webkit-box-pack: justify; 
    -ms-flex-pack: justify; 
    -webkit-justify-content: space-between; 
    justify-content: space-between; 
    -webkit-box-align: center; 
    -ms-flex-align: center; 
    -webkit-align-items: center; 
    align-items: center; 
} 
.mainPanel > div { 
    padding: 0 10px; 
    overflow: hidden; 
    text-overflow: ellipsis; 
    white-space: nowrap; 
    flex: 1 1 25%; 
    border: solid 1px #999; 
} 
.mainPanel > div:nth-child(1) { 
    background: red; 
    display: inline-block; 
} 

.mainPanel > div:nth-child(3) { 
    background: lime; 
} 

.mainPanel > div:nth-child(2) { 
    flex: 900 0 auto; 

    background: yellow; 
    text-align: center; 
} 

我想,在中心的內容不能生長在左和右部分。

我怎樣才能讓左邊和右邊的元素的寬度至多是其內容的大小?我怎樣才能實現左右元素的寬度不能小於其內容?

這是應該的樣子:

enter image description here

回答

0

我不認爲這是可能的CSS3 Flexbox的(還)這樣做。但你可以這樣嗎?

http://jsfiddle.net/fggxq753/1/

z-index: 10; 

因爲你總是希望不管表的內容爲中心的中部文字,我已經從表中刪除,並放置在它具有較高的z-index頂部。它可以在除Safari之外的所有瀏覽器中使用(由於缺少靈活支持)。

如果你想在所有瀏覽器中都能正常工作,我只需要使用display:table;

http://jsfiddle.net/fggxq753/2/

缺點浮動標題是其他細胞可以重疊,如果他們足夠長。爲了解決這個問題,你可以使用標題的中央單元格,並使用javascript自動計算它的填充,但是會變得有點麻煩。

+0

這不是我想要的。我希望中心的內容不能在解決方案中發生的左右部分上增長。 – confile 2015-01-03 13:18:27

0

下面是另一個,也許更容易,方法去實現它

.bar { 
 
    background: yellow; 
 
    line-height: 30px; 
 
    position: relative; 
 
    text-align: center; 
 
    width: 300px;} 
 
    .bar:before, .bar:after { 
 
    padding: 0 10px; 
 
    position: absolute; 
 
    top: 0; 
 
    } 
 
    .bar:before { 
 
    background-color: red; 
 
    content: attr(data-left); 
 
    left: 0; 
 
    } 
 
    .bar:after { 
 
    background-color: lime; 
 
    content: attr(data-right); 
 
    right: 0; 
 
    }
<div class="bar" data-left="L" data-right="Speichern">Style</div>

+0

你能不能請發一個jsfiddle – confile 2014-12-23 13:24:09

+0

我希望Codepen也能工作:http://codepen.io/vkjgr/pen/WbGoMP – 2014-12-24 07:19:03

+0

這不是我想要的。我希望中心的內容不能在解決方案中發生的左右部分上增長。 – confile 2015-01-03 14:59:11