如何控制弹性项目的子 div 高度

How to control child div height of a flex item

描述性 plunker:http://plnkr.co/edit/remH1RtkY1qBk0A7J4Tp?p=preview

我有一个 flexbox 容器,其中包含两个 flex 项目("header" 和 "content")。内容 div 有一个我想控制其高度的子项 div。但是无论我如何设置这个div的高度,高度都保持默认。

这是标记/CSS:

<!DOCTYPE html>
<html>
  <head>
    <style>
      div { padding:15px; }

      .container
      {
        background-color:gold;
        height:500px;
        display:flex;
        flex-flow:column nowrap;
      }
      .header
      {
        background-color:pink;
        /* no flex shrink/grow */
      }
      .content
      {
        background-color:aquamarine;
        flex:1 1;/* allow filling space */
      }
      .myContentItem
      {
        background-color:khaki;
        display:block;
        height:50%;/* <-----------this is ignored */
      }
    </style>
  </head>

  <body>

    <div class="container">
      <div class="header">header<br />yo</div>
      <div class="content">
        <div class="myContentItem">I want this to be 50% the height of content div</div>
      </div>
    </div>

  </body>

</html>

编辑:我知道我可以使用 display:absolute 让它在这个人为的例子中工作。我更好奇 为什么 会发生这种情况,以及如何以适当的方式处理它而不是寻找解决方法。

正是 .content 和 .myContentItem 的填充导致了这种不平等。

.content 上设置 padding:0;,在 .myContentItem 上设置 padding-top:0;padding-bottom: 0;

.content{padding:0;}
.myContentItem{padding-top:0;padding-bottom:0;}

这似乎是一个错误或 not-yet 已实现的功能。弹性项目没有确定的大小(在本例中为高度),因此您无法在 child.

上解析百分比大小

the docs状态:

If a percentage is going to be resolved against a flex item’s main size, and the flex item has a definite flex basis, the main size must be treated as definite for the purpose of resolving the percentage, and the percentage must resolve against the flexed main size of the flex item...

我的理解是 "proper way" 将定义一个明确的弹性基础。所以在你的例子中 flex:1 1; 应该可以解决问题......但是,这是最近的 change/bugfix 所以我希望浏览器支持很少或没有(看起来它已添加到 [=13 的规范中=]).

我的建议是使用 absolute position workaround

另请参阅:https://code.google.com/p/chromium/issues/detail?id=428049 and https://code.google.com/p/chromium/issues/detail?id=346275