【问题标题】:Flexbox body and main min-heightFlexbox 主体和主最小高度
【发布时间】:2016-09-22 17:29:39
【问题描述】:

https://jsfiddle.net/vz7cLmxy/

我试图让身体扩张,但最小高度不起作用。我已阅读其他相关主题,但无法理解。

CSS 和 html

body,
html {
  padding: 0;
  margin: 0;
  min-height: 100%;
}

body {
  display: flex;
  background: #eee;
  flex-direction: column;
}

.menu {
  background: red;
  color: #fff;
  padding: 10px;
}

.wrap {
  display: flex;
}

.sidebar {
  background: #ddd;
  width: 300px;
}

.main {
  background: #ccc;
  flex: 1;
}

.footer {
  background: #000;
  color: #fff;
  padding: 10px;
}
<div class="menu">Menu</div>

<div class="wrap">
  <div class="sidebar">Sidebar</div>
  <div class="main">Main</div>
</div>

<div class="footer">Footer</div>

预期结果是,如果 main 小于 100%,则会拉伸以填充高度。

【问题讨论】:

标签: css height flexbox


【解决方案1】:

在居中的元素上使用flex: 1

.Site {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
}

.Site-content {
  flex: 1;
  background-color:#bbb;
}
<body class="Site">
  <header>This is the header text ☺</header>
  <main class="Site-content">…</main>
  <footer>This is the footer text ☻</footer>
</body>

【讨论】:

  • 谢谢!在 .wrap 上设置 flex: 1 (在我的情况下)和在 html 上设置 width: 100% (而不是 min-height )的组合就可以了!
【解决方案2】:

要让min-height 的相关单位即使在 IE11 中也能正常工作,只需要一个小技巧。

min-height 的本质是当height 小于min-height 时覆盖height。非常清楚!但陷阱是当min-height 有一个现实单元(%vh)并且height 没有设置时。因为是相对的所以没有依据。

对于除 Internet Explorer 之外的所有主要浏览器,一种可能性是将单位从 % 更改为 vh

body {
  min-height: 100vh;
}

对于 Internet Explorer,它需要一个 height(将从 min-height 覆盖):

body {
  height: 1px;
  min-height: 100vh;
}

或者要保留%,规则也必须应用于html

html, body {
  height: 1px;
  min-height: 100%;
}

针对 OP 的跨浏览器解决方案需要 height: 1px on body,当然还有 flex-grow: 1 for .wrap 让它比 menufooter 增长得更快:

body,
html {
  padding: 0;
  margin: 0;
  height: 1px; /* added */
  min-height: 100%;
}

body {
  display: flex;
  background: #eee;
  flex-direction: column;
}

.menu {
  background: red;
  color: #fff;
  padding: 10px;
}

.wrap {
  display: flex;
  flex-grow: 1; /* added */
}

.sidebar {
  background: #ddd;
  width: 300px;
}

.main {
  background: #ccc;
  flex: 1;
}

.footer {
  background: #000;
  color: #fff;
  padding: 10px;
}
<div class="menu">Menu</div>

<div class="wrap">
    <div class="sidebar">Sidebar</div>
    <div class="main">Main</div>
</div>

<div class="footer">Footer</div>

【讨论】:

  • height: 1px 的问题是您失去了内容的自动缩放功能。所以在现实生活中min-height 也可以做成height。失去自动缩放意味着内容永远不会使元素超出min-height,从而使属性变得无用。
  • @GuidoBouman @kmgt 我刚刚遇到了这个问题,将height 设置为fit-content 而不是1px 对我有用。它为height 提供了一个min-height 可以覆盖的值,但保留了否则会丢失的自动缩放功能。
  • 你会猜到的! IE 不喜欢fit-contentcaniuse/fit-content
猜你喜欢
  • 1970-01-01
  • 2015-11-15
  • 1970-01-01
  • 2013-11-19
  • 2013-01-31
  • 2023-03-26
  • 2018-04-21
  • 2017-07-06
  • 2018-06-01
相关资源
最近更新 更多