CSS3 column layout with dynamic number of columns

Christian Schnorr picture Christian Schnorr · Dec 15, 2013 · Viewed 7.4k times · Source

I have a set of images that I want to display in the following pattern:

[1] [4] [7] [10] [13]
[2] [5] [8] [11] ...
[3] [6] [9] [12]

I know that I can always manually group 3 images into a div.column or something similar, but I want to achieve this layout with as simple HTML as possible. The images are 225x150.


Currently, I have the following HTML:

<div class='album'>
    <img src='img/01.jpg' />
    <img src='img/01.jpg' />
    ...
</div>

And here's my stylesheet:

.album {
    background: #faa;
    display: block;
    -webkit-column-count:2;
    -webkit-column-gap: 10px;
    height: 450px;
    width: 460px;

}
.album img {
    display: block;
    width: 100%;
}

Chapter 8.2 in the specs describes that if I specify a height and the content won't fit in, more columns are created as needed, which is basically just what I want.

As you can see, I specified a background color for the .album. This does only cover the first two columns though, since I set the width to 460px. However, I really need an element that has the exact size/width of the album's content, i.e. an element wrapping the album with that exact size.

None of the possibilities I tried seemed to work tho. (100%, auto, played with overflow as well)

Does anyone have an idea on how I could create such a wrapper element for my albums?

Answer

cimmanon picture cimmanon · Dec 15, 2013

You may be stuck using Flexbox for this purpose, since using columns within inline elements (inline-block, etc.) causes some browsers to miscalculate the width of the element.

http://codepen.io/cimmanon/pen/vuxjF

.album {
  background: #faa;
  height: 480px;
  padding: 5px;
  display: -ms-inline-flexbox;
  display: -webkit-inline-flex;
  -webkit-flex-flow: column wrap;
  -ms-flex-flow: column wrap;
  flex-flow: column wrap;
  -ms-flex-align: start;
  -webkit-align-items: flex-start;
  align-items: flex-start;
}
@supports (flex-wrap: wrap) {
  .album {
    display: inline-flex;
  }
}

.album img {
  margin: 5px;
}