10

Assume we have a container, whose children have to fill it in columns. The container is limited in height and has to be as wide/narrow as need for all the descendants to fit. It should look like this:

enter image description here

To make this I try flexbox. The question is: is it possible to make it shrink-to-fit?

  • float:left: in Chrome doesn't do the trick at all, in Firefox the container has the width of only one column - example 1
  • position:absolute: it doesn't contribute to normal flow, so discard this.

For now I narrow down the browser range to Chrome and FF.

The HTML:

<div class="flexcontainer wrap column">
    <div></div>
    <div></div>
    ...
</div>

The CSS:

.flexcontainer{
    display: flex;              /* make it a flexbox */
    flex-flow: column wrap;     /* make it a column container, and fill them one after another */

    align-content: stretch;
    align-items: center;
    justify-content: center;

    float: left;                /* shrink-to-fit */

    max-height: 450px;          /* limit the height */
    min-height: 300px;
}
.flexcontainer > div {
    height: 100px;            
    margin: 3px;
    width: 100px;               /* set the width of descendants */
}

Thanks!

bonflash
  • 714
  • 6
  • 17
  • Is there a maximum number of items? – toonice Oct 14 '15 at 07:46
  • Also, can your page extend beyond the normal width and height of the viewport? – toonice Oct 14 '15 at 07:48
  • Any update on how you solved this or is jquery the only way? – d_rail Jan 13 '16 at 20:32
  • Possible duplicate of [How can I make a display:flex container expand horizontally with its wrapped contents?](http://stackoverflow.com/questions/23408539/how-can-i-make-a-displayflex-container-expand-horizontally-with-its-wrapped-con) – Mark Amery Dec 18 '16 at 14:48

1 Answers1

1

Javascript solution:

$(document).ready(function() {
 $('.flexcontainer').each(function( index ) {
     var parentHeight = $(this).outerHeight();
     var childHeight = $(this).children().outerHeight();
     var childCount = $(this).children().length;
     var cols = Math.ceil(childHeight*childCount/parentHeight);

     var childWidth = $(this).children().outerWidth();
     var padding = 15;
     $(this).width(childWidth*cols+padding);
    })
});
David Machado
  • 430
  • 2
  • 10