2014-03-31 67 views
0

enter image description here 所以我想在這裏實現的是讓紅框固定寬度,比如400px,它在頁面上水平居中。紅色框的任何一邊都是一個綠色框和一個寬度可變的淡紫色盒子,可以水平填充窗口的其餘部分,並且可以適應窗口大小。CSS - 可以實現這種流體佈局嗎?

因此,在一個更大的顯示器上,綠色和淡紫色的盒子將被水平拉伸,並且頁面中間的紅色框將保持相同的寬度。

解決方案需要在IE 8及更高版本中工作,儘管我對只能在IE9 +上運行的解決方案感興趣。

+0

@CBroe這個問題有盒用它們之間的空格,所以雖然表格單元方法起作用,但它需要更多的嵌套div。請注意,這不是白色邊框,而是實際空間。下面的答案中提供了更好的解決方案。還有一個使用Calc的前瞻性解決方案,長期來看效果更好。 – user1209203

回答

2

I created this quick JSFiddle hack for you.

基本上,我們讓這三個div的浮動彼此相鄰,給中間一固定的寬度,並使用其它兩個以下標記:

width:50%; 
padding-left: 150px; 
margin-left: -150px; 
box-sizing: border-box; 

width:50%; 
padding-right: 150px; 
margin-right: -150px; 
box-sizing: border-box; 

其中150等於中間div寬度的一半。

+1

中間'div'應該是400px,所以一半是200. :) –

+1

謝謝,這很好,但需要-moz-box-sizing:border-box;對於Firefox – user1209203

+0

@RenéRoth實際上這在IE 8中不起作用 – user1209203

4

您可以使用calc來解決這個問題:

HTML:

<div class="green"></div> 
<div class="red"></div> 
<div class="lilac"></div> 

CSS:

html, body { 
    width: 100% 
} 

.green { 
    width: calc((100% - 400px)/2); //takes the total space, minus the red box space, divided by two. 
    height: 200px; 
    background: green; 
    float: left; 
} 

.red { 
    width: 400px; 
    height: 200px; 
    background: red; 
    float: left; 
} 

.lilac { 
    width: calc((100% - 400px)/2); 
    height: 200px; 
    background: lavender; 
    float: left; 
} 

概念證明:http://jsfiddle.net/yERs7/

+1

好的解決方案,但請記住,calc()在某些較舊的移動瀏覽器中不起作用。 –

+1

@RenéRoth啊,道歉。我經常忘記傳統和移動瀏覽器。 –

+0

別擔心,我認爲你的解決方案是可取的! –

4

您可以使用display: table,有充分的即使與兼容,因爲你問

例如在codepen:http://codepen.io/anon/pen/emCFy/


標記:

<div> 
    <section style="background: #91ee93"> 
    Green</section> 
    <section style="background: #ee8c8f" role="main"> 
    Red</section> 
    <section style="background: #e48fec"> 
    Pink</section> 
</div> 

的CSS

div { 
    display: table; 
    table-layout: fixed; 
    width: 100%; 
} 

section { 
    display: table-cell; 
} 

section[role] { 
    width: 400px; 
} 
+0

這是工作,但至關重要的是我無法獲得紅色框兩側的空間。 – user1209203

+0

您可以使用填充內部部分或使用應用於紅色框的白色邊框左側/右側(請參閱更新的示例) – fcalderan