使带有收缩配合柱的柔性容器

时间:2014-08-21 07:52:36

标签: css flexbox shrink

假设我们有一个容器,其子容器必须用列填充它。容器的高度有限,并且必须与所有后代适合的宽/窄一样宽。它应该是这样的:

enter image description here

要做到这一点,我尝试flexbox。问题是:是否有可能使其缩小适合?

  • float:left:在Chrome中根本没有做到这一点,在Firefox中,容器的宽度只有一列 - example 1
  • position:absolute:它对正常流量没有贡献,所以放弃它。

目前我将浏览器范围缩小到Chrome和FF。

HTML:

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

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 */
}

谢谢!

2 个答案:

答案 0 :(得分:1)

JavaScript解决方案:

$(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);
    })
});

答案 1 :(得分:-1)

ol&#39; float/clear诀窍:

float: left;
clear: left;

它会强制元素缩小到其内容的大小。有时候更简单更好。

fiddle to see this code in action

HTML:

<div class="container">
  <div class="left ">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
  <div class="left ">
    <div class="box"></div>
    <div class="box"></div>
  </div>
</div>

CSS:

.container{ 
  float: left;
  clear: left;
  border: solid 2px black; 
}

.left{ float: left }

.box{
  display: block;
  background-color: orange;
  border: solid 1px green;
  height: 20px;
  width: 20px;
}