2013-06-25 23 views
0

我想實現這一點:動態地(流體)隔開的多元素(如對齊)

enter image description here

這些只是其中有一個流體動寬度的容器內的任何元素。 我想將N個項目放在一行中,它們之間有動態間距,所以 我的佈局總是有4個並且也是響應式的。

訣竅是不使用每行的任何包裝元素,只是最小的DOM與任何CSS。

Live Playground

+0

嘗試,看看部份文章:HTTP://barrel2013.staging .barrelclient.com /博客/文本對齊-justify-and-rwd/ – fcalderan

+0

@Fabrizio Calderan - 他的解決方案要求我知道我有多少元素 – vsync

回答

0

您將要使用%寬度和幅度。

像這樣的東西(從你的例子所):

ul{ list-style:none; } 

li{ 
    float: left; 
    display:block; 
    width:21.7%; 
    height:50px; 
    background:red; 
    margin: 0 4.4% 4.4% 0; 
} 
li.z{ 
    margin-right: 0; 
} 

li:nth-child(2n){ 
    background:blue; 
} 

注意,我添加了一個「Z」類到你的最後一個元素,即每4個。

HTH。

+0

不能與百分比一起工作......請使用操場來證明您的理論 – vsync

+0

http://jsbin.com/ irijuz/4/ – sturdynut

+0

這是它的現場版本,我更新了一點,希望這是你想要的。讓我知道如果不是,我會看看我能否進一步幫助你。 – sturdynut

0

使該功能在加載和調整大小時觸發。

的jsfiddle:http://jsfiddle.net/Bushwazi/j8PKn/

HTML:

<ul> 
    <li></li> 
    <li></li> 
    <li></li> 
    <li></li> 
    <li></li> 
    <li></li> 
</ul> 

CSS:

ul { 
    list-style:none; 
    width:100%; 
    min-width:400px; 
} 
ul li { 
    width:50px; 
    display:inline-block; 
    float:left; 
    height:50px; 
    margin-bottom:50px; 
} 
ul li:nth-child(2n+1) { 
    background:#ff0000; 
} 
ul li:nth-child(2n+2) { 
    background:#0096ff; 
} 

JS:

var organize = function(){ 
    // get the outer width 
    shWidth = $('ul').width(); 
    console.log(shWidth); 
    // generate the width of each column 
    colWidth = shWidth/4; 
    console.log(colWidth); 
    // add the correct margin to the first column 
    $col1 = $('ul li:nth-child(4n+1)'); 
    $col1.css({'margin':'10px ' + (colWidth - 50) +'px 10px 0'}); 
    // add the correct margin to the center columns 
    $colCenter = $('ul li:nth-child(4n+2), ul li:nth-child(4n+3)'); 
    $colCenter.css({'margin':'10px ' + (colWidth - 50)/2 +'px'}); 
    // add the correct margin to the 4th columns 
    $col4 = $('ul li:nth-child(4n+4)'); 
    $col4.css({'margin':'10px 0 10px ' + (colWidth - 50) +'px'}); 
} 


organize(); 
+0

你用每個元素的容器..我更喜歡不..只是與元素本身 – vsync

+0

我剛剛閱讀你的其他意見。沒有其他的HTML標記或邊距,你想要的是不可實現的。 –