2015-01-14 68 views
1

在我的情況下,孩子號碼從服務器端返回。如果少於6個孩子,我需要添加一個虛擬孩子,這個虛擬孩子會留在父母的左邊。CSS讓最後一個孩子動態地取得父母留下的寬度

例如:

1的情況有兩個孩子的 enter image description here 2有三個孩子的 enter image description here

fiddle

<div id="container"> 
    <div class="child"></div> 
    <div class="child"></div> 
    <div class="child"></div> 
    <div class="big-child"></div> 
</div> 
#container{ 
    width: 100%; 
    height: 200px; 
    background-color: gray; 
} 

#container > div { 
    float: left; 
    background-color: black; 
    width: 100px; 
    height: 100px; 
    margin-right: 20px; 
} 

.big-child { 
    width: 59%!important; 
    margin-right: 0px!important; 
} 

情況下,我怎麼能只用CSS實現這一點,withoud dinamically改變孩子的寬度與JavaScript?

UPDATE

找到好website產生取決於你的箱子需要CSS代碼。

+0

任何瀏覽器的要求/支持? – fcalderan

+0

在我的項目中,我們支持IE10,Chrome和Firefox版本並非如此。 – kuldarim

回答

1

在現代的瀏覽器可以使用flexbox

http://codepen.io/anon/pen/yyMgQL

CSS:

#container { 
    display: -ms-flexbox; /* IE 10 syntax */ 
    display: flex; 
    width: 100%; 
    height: 200px; 
    background-color: gray; 
} 

#container > div { 
    background-color: black; 
    width: 100px; 
    height: 100px; 
    margin-right: 20px; 
} 

#container > div.big-child { 
    -ms-flex-grow: 1; /* IE 10 syntax */ 
    flex-grow: 1; 
    margin-right: 0; 
} 

進一步的信息:
- http://css-tricks.com/snippets/css/a-guide-to-flexbox/
- http://css-tricks.com/old-flexbox-and-new-flexbox/

瀏覽器支持:http://caniuse.com/#feat=flexbox
(注意IE10支持,但它實現了一個較舊的語法)

0

如果您想使用浮動,您可以使用最後一個孩子上的overflow:hidden;來強制它佔據剩餘的空間。

替代解決方案可以使用flexbox(取決於您所需的瀏覽器支持)或CSS表格。

#container { 
 
    width: 100%; 
 
    height: 200px; 
 
    background-color: gray; 
 
} 
 
#container > div { 
 
    box-sizing: border-box; 
 
    margin-right: 0; 
 
    height: 100px; 
 
} 
 
#container > div:not(:last-child) { 
 
    margin-right: 10px; 
 
} 
 
.child { 
 
    float: left; 
 
    background-color: black; 
 
    width: 100px; 
 
} 
 
.big-child { 
 
    overflow: hidden; 
 
    background-color: black; 
 
    margin: 0 20px; 
 
}
<h4>Three Blocks</h4> 
 
<div id="container"> 
 
    <div class="child"></div> 
 
    <div class="child"></div> 
 
    <div class="child"></div> 
 
    <div class="big-child"></div> 
 
</div> 
 

 
<h4>Two Blocks</h4> 
 
<div id="container"> 
 
    <div class="child"></div> 
 
    <div class="child"></div> 
 
    <div class="big-child"></div> 
 
</div>

相關問題