簡體   English   中英

如何均勻地在兩列中顯示動態內容?

[英]How to display dynamic content in two columns evenly?

我在頁面上加載了動態內容,因此未指定數量的元素。 我需要它們在兩列之間均勻分布,所以我認為將它們的寬度設置為50%並將它們向左浮動就可以了。

<div class="element">
    <p>My content goes here!</p>
</div>

.element{float:left;width:50%;}

一個例子: https//jsfiddle.net/fft75mu4/

但在我的例子中,藍色元素上方有一個間隙,因為右邊元素比第一個元素高。 推薦的解決方案是什么? 我認為這是一個常見的問題?

我寧願不在CSS中創建實際的列,因為內容是動態的,元素可能非常高/短,所以在左邊放5和在右邊放5並不總是有效。

根據您希望的瀏覽器支持,CSS列可能是一個解決方案嗎?

http://caniuse.com/#feat=multicolumn

body {
    column-count: 2;
}

.element {
    break-inside: avoid;
}

https://jsfiddle.net/erykpiast/fft75mu4/11/

您可以通過不同的方式完成此操作,其中之一(左列 - “floatLeft”類,右列 - “floatRight”類):

 .element{width:50%;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;} .floatLeft{ float:left; } .floatRight{ float:right; } .blue{background-color:#3aa9e3} .red{background-color:#f15743;} .green{background-color:#8aba56;} 
 <div class="element red floatLeft"> <p>My content goes here! My content goes here! My content goes here! My content goes here!</p> </div> <div class="element green floatRight"> <p>My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here!</p> </div> <div class="element blue floatLeft"> <p>My content goes here! My content goes here! My content goes here! My content goes here!</p> </div> 

你需要使用javascript。 有一個名為masonry的輕量級庫( http://masonry.desandro.com/ )可以幫助您實現您想要的效果。

Ked答案更干凈,但您也可以嵌套div標簽。 像這樣的東西:

 .element{width:50%;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;} .blue{background-color:#3aa9e3} .red{background-color:#f15743;} .green{background-color:#8aba56;} .floatLeft{ float:left; } .floatRight{ float:right; } 
 <div class="element floatLeft"> <div class="red floatLeft"> <p >My content goes here! My content goes here! My content goes here! My content goes here!</p> </div> <div class="blue floatRight"> <p>My content goes here! My content goes here! My content goes here! My content goes here!</p> </div> </div> <div class="element green floatRight"> <p>My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here! My content goes here!</p> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM