如何使flex-grow行为不贪婪?

时间:2014-07-31 14:35:41

标签: css3 flexbox

illustration

标记:

<div class="playground">
  <div class="red">
    <div class="child">I don't need all this space, but my parents are greddy. : (</div>
  </div>
  <div class="blue">I want to grow big!</div>
</div>

样式表:

.playground {
  width: 500px; height: 500px; background: #ccc; display: flex; flex-direction: column;
}

.red,
.blue {
  width: 100%;
}

.red {
  flex: 1; background: rgba(255,0,0,.5);

  .child {
    background: rgba(255,255,255,.5); padding: 10px; margin: 10px;
  }
}

.blue {
  background: rgba(0,0,255,.5); min-height: 100px; max-height: 300px;
}

http://jsbin.com/waset/1/

在上面的例子中,

  • 红色容器设置为使用所有可用空间(flex-grow)。
  • 红色容器与蓝色共享空间。
  • 蓝色max-height: 300px
  • 红色内容并未占据所有高度。如果红色不贪婪,它会额外赠送200px到蓝色

如何让红色不贪心?

4 个答案:

答案 0 :(得分:1)

尝试将flex:1;添加到.blue
顺便说一句,您在width

中拼错了.red,.blue

答案 1 :(得分:0)

如果我理解正确,您可以在flex-grow.red上使用.blue,并为蓝色提供非常大的值。使用flex-grow代替flex速记会将flex-basis默认为auto。因此,flex-basis将基于内容,然后只有在考虑初始内容后才会分配剩余空间。

.blue上非常大的值会导致它消耗几乎所有剩余空间,直到达到其最大宽度。

.red {
    flex-grow: 1;
    background: rgba(255, 0, 0, .5);

    .child {
        background: rgba(255, 255, 255, .5);
        padding: 10px 10px;
        margin: 10px;
    }
}

.blue {
    flex-grow: 999;
    background: rgba(0, 0, 255, .5);
    min-height: 100px;
    max-height: 300px;
}

答案 2 :(得分:0)

这是你在找什么?我不记得我在哪里学到了这种技术,但是当我再次访问网站时,我会发布信用。我创建了两个flexbox,一个蓝色和红色,当你将鼠标悬停在它们上面时,每个都会扩展。希望这可以帮助。

    <!DOCTYPE html>
    <html lang="en">
      <head>

       <style>
       .flx
       {
          width: 400px;
          height: 200px;
          font: 12px auto;

          display: -webkit-flex;
          -webkit-flex-direction: column;
          display: flex;
          flex-direction: column;
       }

       .flx > div
       {
          -webkit-flex: 1 1 auto;
          flex: 1 1 auto;
          width: 50px;

          -webkit-transition: width 0.2s ease-out; /*adjust speed of size change*/
  transition: width 0.2s ease-out;

       }
       .flx > div:nth-child(1){ background : red; }
       .flx > div:nth-child(2){ background : blue; }
       .flx > div:hover    /*adjust size when you hover*/
       {

            width: 200px;
       }
       </style>  

     </head>
     <body>
      <div class="flx">
        <div>red box</div>
        <div>blue box</div>
      </div>
     </body>
    </html>

答案 3 :(得分:0)

我认为您可以将flex: 1;代替flex-grow设置为.red.blue。这适用于Facebook的瑜伽布局。