What is the best way to create an asymmetrical two-column grid with dynamic content?

我的梦境 提交于 2020-01-02 19:31:39

问题


I have dynamic content flowing into a two-column grid. Flex box is a nice solution, but it forces the rows to be the same height, creating some awkward white space when one has more content. Does anyone know of a lightweight solution that can achieve what is hopefully clearly communicated in the below image?

Code for my current solution:

.grid-container {
  display:flex;
  flex-wrap: wrap;
  justify-content:space-between;
  height:auto;
  height:700px;
  overflow-y:scroll;
}
.contained-cell{
  width:48.5%;
  padding:40px 20px;


回答1:


In your code, the flex items are aligned in a row by default (flex-direction: row). And also by default, flex items will stretch to occupy the full available height of the container (align-items: stretch) – thus creating equal height columns.

You could use align-items: flex-start to make each flex item stretch only enough to contain its content. But then, as you've noted, this doesn't change the height of the row, and the result is lots of vertical white space between items.

The standard solution for this layout is jQuery Masonry which, as they write on their website, works by placing elements in optimal position based on available vertical space, sort of like a mason fitting stones in a wall. That's one option.

Keeping to CSS, however, another flexbox solution is changing the flex-direction from row to column. With this set-up, equal height rows don't apply, vertical whitespace isn't an issue, and each flex item can be its own height.

Here's a demo: http://jsfiddle.net/8rq0maL4/1/



来源:https://stackoverflow.com/questions/33552782/what-is-the-best-way-to-create-an-asymmetrical-two-column-grid-with-dynamic-cont

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!