How to control child div height of a flex item

孤者浪人 提交于 2020-01-31 18:33:49

问题


Descriptive plunker: http://plnkr.co/edit/remH1RtkY1qBk0A7J4Tp?p=preview

I have a flexbox container containing two flex items ("header" and "content"). The content div has a single child div that I want to control the height of. But no matter how I set the height of this div, the height stays default.

Here's the markup / 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>

edit: I am aware that I could use display:absolute to make it work in this contrived example. I'm more curious though why this happens, and how to deal with it in a proper way instead of finding a workaround.


回答1:


This would appear to be a bug or not-yet implemented feature. The flex item has no definite size (height in this case), so you cannot resolve a percentage size on the child.

The the docs state:

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...

The way I understand this is that the "proper way" would be to define a definite flex basis. So in your example flex:1 1; should do the trick... however, this is a very recent change/bugfix so I would expect little to no browser support (looks like it was added to the spec in march 2014).

My suggestion would be to use the absolute position workaround.

See also: https://code.google.com/p/chromium/issues/detail?id=428049 and https://code.google.com/p/chromium/issues/detail?id=346275.




回答2:


It is the padding of .content and .myContentItem that gives you that inequality.

Set padding:0; on .content, and padding-top:0; and padding-bottom: 0; on .myContentItem.

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


来源:https://stackoverflow.com/questions/29049715/how-to-control-child-div-height-of-a-flex-item

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!