Make flex container with columns shrink-to-fit
Asked Answered
A

1

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!

Analeptic answered 21/8, 2014 at 7:52 Comment(4)
Is there a maximum number of items?Moujik
Also, can your page extend beyond the normal width and height of the viewport?Moujik
Any update on how you solved this or is jquery the only way?Abbotson
Possible duplicate of How can I make a display:flex container expand horizontally with its wrapped contents?Rijeka
G
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);
    })
});
Georganngeorge answered 28/8, 2019 at 23:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.