6

I'm creating a card-style layout, in which individual cards stack vertically. At higher screen widths, more and more columns of cards are used - using as little vertical space as possible.

I'm using a flex-flow: column wrap layout to do this. However, what I find is that the container is required to have a height or max-height in order to encourage the cards to wrap. Given that the number of cards and their individual size may change, I can't tell what this height will optimally be without cutting off items or having excessive space below.

Can anyone tell me if this is possible, or if I'm doing something wrong?

Snippet attached.

.card-container {
  display: flex;
  flex-flow: column wrap;
  align-items: stretch;
}
.card {
  flex: 0 0 auto;
  width: 15rem;
  margin: 0.5rem;
  background-color: #f4f4f4;
  /* max-height: ??? */
}
<div class="card-container">
  <div class="card" style="height: 20em"></div>
  <div class="card" style="height: 17em"></div>
  <div class="card" style="height: 5em"></div>
  <div class="card" style="height: 10em"></div>
  <div class="card" style="height: 21em"></div>
  <div class="card" style="height: 10em"></div>
  <div class="card" style="height: 17em"></div>
  <div class="card" style="height: 8em"></div>
  <div class="card" style="height: 20em"></div>
  <div class="card" style="height: 16em"></div>
  <div class="card" style="height: 19em"></div>
  <div class="card" style="height: 10em"></div>
  <div class="card" style="height: 5em"></div>
</div>
j08691
  • 204,283
  • 31
  • 260
  • 272
Ben Cox
  • 1,393
  • 10
  • 28
  • I've often encountered this problem, as well. In order to get flex items to wrap in column-direction, a height needs to be defined. SMH. Problem doesn't occur in row-direction. I haven't yet found a solution. Worse, once you solve that issue, you'll need to deal with this: http://stackoverflow.com/q/33891709/3597276 – Michael Benjamin Dec 02 '15 at 19:02

1 Answers1

0

For achieving this, you need to set max-height for the flex container, not flex items because you want the flex items to be aligned in columns and increase the columns for wider screens and you don't want the flex items to change in size, so set this relative value for the flex container:

.card-container {
    max-height: 100vh
}

Add this to the flex container. Here "vh" is a relative unit that stands for "Viewport Height". 1 vh = 1% of the height of the viewport. Viewport = the browser window size. If the viewport is 50 cm high, 1 vh = 0.5 cm.

So no matter how wide the screen is, how many cards you insert, how big the cards will be, multiple columns will be used whenever the height of the content is more than the height of the viewport.

These will also create horizontal scroll bars on displays that are set on narrower widths than the content. So if you don't want the scroll bars to appear, this can be fixed using media queries.

Zed Strong
  • 11
  • 4