3

I would like to create a two column layout (CSS only, no javascript).

There are a few requirements that make this complicated:

  1. Container starts with a specific height (e.g. 200px)
  2. There are two columns
  3. Items fill Column 1, then if more space is needed fill Column 2.
  4. If Column 1 & Column 2 are full, then expand the height of the container.

Detailed example here.

Bad enter image description here

Good

Elements first fill Column 1: enter image description here

Next, elements fill Column 2: enter image description here

When the container's minimum height is reached, the container expands and elements reflow between the two columns: enter image description here

Don P
  • 60,113
  • 114
  • 300
  • 432

2 Answers2

3

Flexbox + CSS columns gets you really close...

http://codepen.io/simshanith/pen/ZLLvGB?editors=1100

HTML:

<div class="container">
  <div class="columns">
    <div class="item">1</div>
    <!-- etc. -->
  </div>
</div>

CSS:

.container {
  background: rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  min-height: 200px;
  width: 600px;
}

.columns {
  column-count: 2;
  column-gap: 0;
  flex: 1;
}

.item {
  display: block;
  box-sizing: border-box;
  padding: 10px;
  border: 1px solid blue;
  width: 100%;
  -webkit-column-break-inside: avoid;
  /* Chrome, Safari, Opera */
  page-break-inside: avoid;
  /* Firefox */
  break-inside: avoid;
  /* IE 10+ */
}

However, the first column is not filled to 200px. CSS Columns optimize for shortest, so the second column will appear with at least 2 items.

Shane Daniel
  • 959
  • 1
  • 7
  • 14
2

With flexbox, you can expand the container vertically when flex-direction is row. As you have noted, however, this lays out flex items horizontally – left-to-right (in LTR writing mode) and then back, like an old typewriter.

In flex-direction: column, items are laid out top-to-bottom, and the container expands horizontally.

What you want – for columns to stack top-to-bottom, expanding the container vertically (like the Pinterest layout) – is not currently possible with flexbox.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701