2011-08-13 126 views
20

我有一個容器寬度爲100%的頁面,所以它的整個屏幕寬度,我在網格結構中有幾個DIV,它們都有浮動:留在它們上面,沒有設置寬度,只有10px的邊距。用CSS填充div來填充父容器的寬度

是否有一種方法,使用CSS或jQuery,使div填充整個寬度並證明自己適合差距,所以邊距會根據屏幕大小而變化。

+0

你說的div目前沒有固定的寬度,但確實有一定的餘量。你打算讓div的寬度是固定的,並且它們之間的空間是流暢的? – shanethehat

+0

是的,這正是我想要的 – benhowdle89

回答

28

在這個線程沒有JavaScript在所有瀏覽器包括IE 6的工作原理純CSS/HTML解決退房thirtydot的答案

Fluid width with equally spaced DIVs

http://jsfiddle.net/thirtydot/EDp8R/

HTML:

<div id="container"> 
    <div class="box1"></div> 
    <div class="box2"></div> 
    <div class="box3"></div> 
    <div class="box4"></div> 
    <span class="stretch"></span> 
</div>​ 

CSS:

#container { 
    border: 2px dashed #444; 
    height: 125px; 

    text-align: justify; 
    -ms-text-justify: distribute-all-lines; 
    text-justify: distribute-all-lines; 

    /* just for demo */ 
    min-width: 612px; 
} 

.box1, .box2, .box3, .box4 { 
    width: 150px; 
    height: 125px; 
    vertical-align: top; 
    display: inline-block; 
    *display: inline; 
    zoom: 1 
} 
.stretch { 
    width: 100%; 
    display: inline-block; 
    font-size: 0; 
    line-height: 0 
} 

.box1, .box3 { 
    background: #ccc 
} 
.box2, .box4 { 
    background: #0ff 
} 

+1

偉大的,除了IE6。 – Webars

+9

好東西IE6現在出來:) –

+4

偉大的事情現在IE7也出來了:D – Ergec

2

如果以百分比(即寬度,邊距,填充)指定所有尺寸,則可以使用CSS進行此操作。

或者,如果你想有一個特定的保證金或填充,你可以使用jQuery

$(window).resize(function() { 
    var $columns = $('.column'), 
     numberOfColumns = $columns.length,    
     marginAndPadding = 0, 
     newColumnWidth = ($('#container').width()/numberOfColumns) - marginAndPadding, 
     newColumnWidthString = newColumnWidth.toString() + "px"; 

    $columns.css('width', newColumnWidthString); 
}).resize(); 
9

使用CSS3這現在超級簡單。

UPDATE

增加了微軟IE瀏覽器的支持(相信它或不...)。我不太確定FF的東西,因爲Mozilla改變了一些東西。我沒有那麼多時間。因此,如果有人也許可以糾正我...

UPDATE II

遷代碼片斷

.container { 
 
    border: 1px solid black; 
 
    display: -webkit-box; 
 
    -webkit-box-pack: justify; 
 
    -webkit-box-align: center; 
 
    display: -moz-box; 
 
    -moz-box-pack: justify; 
 
    -moz-box-align: center; 
 
    display: -ms-flexbox; 
 
    -ms-flex-pack: justify; 
 
    -ms-flex-align: center; 
 
    display: box; 
 
    box-pack: justify; 
 
    box-align: center; 
 
} 
 
.child { 
 
    background-color: red; 
 
}
<div class="container"> 
 
    <div class="child"> 
 
    Some Content 
 
    </div> 
 
    <div class="child"> 
 
    Some Content 
 
    </div> 
 
    <div class="child"> 
 
    Some Content 
 
    </div> 
 
</div>

+2

上測試,請考慮使用:使用「space-between」(http://css-tricks.com/snippets/css/a-guide-to-flexbox/)穩定(相對於整個Flexbox的穩定性) – kurttheviking