flex和height属性有什么区别?

时间:2018-05-10 04:44:00

标签: html css css3 flexbox

鉴于以下示例,如果页面使用flex,两者都将填写中心以消耗页面中的剩余空间。我倾向于在正文中使用css属性flex vs height。在将一个应用于另一个时需要考虑是否存在差异?

CSS

.page {
  display: flex;
  flex-direction: column;
}

.header {
  height: 100px;
}

.body {
  flex: 1; // vs height: 100%;
}

.footer {
  height: 40px;
}

HTML

<div class="page">
   <div class="header">Sample Header</div>
   <div class="body">Sample Body</div>
   <div class="footer">Sample Footer</div>
</div>

3 个答案:

答案 0 :(得分:1)

弹性和高度之间存在巨大差异。

首先回答你的问题。

  1. 高度100%不使用剩余空间。如果页面dom为height 200px;,则它将使用父级的所有空格,然后正文也将为height: 200px;

  2. 这里的Flex将是正确的解决方案,以填补空间(flex: 1)。

    Flex不仅仅是填充空间,更多的是布局,它对孩子的影响,它们如何定位和对齐。

答案 1 :(得分:1)

当您将元素设置为flex: 1时,会将其细分为:

  • flex-grow: 1
  • flex-shrink: 1
  • flex-basis: 0

在列方向容器中(与您一样),上面的flex属性垂直应用。这意味着flex-basisheight是等效的属性。

flex-basis = height (in a column-direction container)

flex-basis: 0height: 100%之间存在明显差异。它与height: 0height: 100%的区别相同。

在您的情况下,如果.header.footer消耗140px的垂直空间,则将中间项(.body)设置为height: 100%通常会导致溢出。

但由于flex容器的初始值为flex-shrink: 1,因此允许flex项缩小,这不会发生。但是,在我看来,它仍然是草率和不精确的编码。

通过将.body设置为flex: 1,您可以将高度设置为0,同时允许其使用flex-grow: 1消耗自由高度。在这种情况下,我会说这个解决方案效率更高。

更多详情:

答案 2 :(得分:0)

尝试以下代码

&#13;
&#13;
.page {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.header {
  height: 100px;
   display: flex;
  align-items: center;
  justify-content: center;
}

.body {
    display: flex;
  flex-direction:  column;
    height: 80vh;    
      align-items: center;
  justify-content: center;  

}

.footer {
  height: 40px;
    display: flex;
     align-items: center;
  justify-content: center;
}
&#13;
<div class="page">
   <div class="header">Sample Header</div>
   <div class="body">Sample Body</div>
   <div class="footer">Sample Footer</div>
</div>
&#13;
&#13;
&#13;