【问题标题】:Content in flexbox with minimum sizeflexbox 中最小尺寸的内容
【发布时间】:2018-07-20 03:01:20
【问题描述】:

我正在使用 flexbox 在其容器中垂直对齐具有可变高度的 div(我对其他选项持开放态度)。 但是当容器小于内容时,我很难获得可靠的滚动行为。

html,
body,
.app {
  height: 100%;
}

.app {
  background-color: blue;
  color: white;
}

.app header {
  height: 80px;
  background-color: red;
}

.app .container {
  display: flex;
  flex-direction: column;
  background-color: black;
  height: calc(100% - 80px);
  align-items: center;
  justify-content: center;
  overflow: scroll;
}

.app .container .content {
  width: 300px;
  height: 200px;
  background-color: yellow;
  color: black;
}
<link rel="stylesheet prefetch" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<div class="app">
  <header>Header</header>
  <div class="container">
    <div class="content">
      Variable content height
    </div>
  </div>
</div>

非常感谢!

【问题讨论】:

  • 容器怎么比内容小?
  • @Paulie_D 可能他指的是容器的固定高度,当内容超过时可能会滚动(只是争论没有一个真实的例子)
  • 只需将min-height:200px 添加到您的内容中 - 因为其中没有任何内容,flex 正在调整其大小以适应父级,这就是您无法滚动的原因

标签: html css flexbox vertical-alignment


【解决方案1】:

保持overflow:auto,不需要使用列作为方向,只需保持行。然后依靠margin:auto 保持元素居中:

没有溢出且居中的示例:

html, body, .app {
  height: 100%;
}
body {
 margin:0;
}

.app {
  background-color: blue;
  color: white;
}
.app header {
  height: 80px;
  background-color: red;
}
.app .container {
  display: flex;
  flex-direction: row;
  background-color: black;
  height: calc(100% - 80px);
  justify-content: center;
  overflow: auto;
}
.app .container .content {
  width: 300px;
  height:100px;
  background-color: yellow;
  color: black;
  margin:auto;
}
<div class="app">
  <header>Header</header>
  <div class="container">
    <div class="content">
      Variable content height
    </div>
  </div>
</div>

溢出和滚动示例

html, body, .app {
  height: 100%;
}
body {
 margin:0;
}

.app {
  background-color: blue;
  color: white;
}
.app header {
  height: 80px;
  background-color: red;
}
.app .container {
  display: flex;
  flex-direction: row;
  background-color: black;
  height: calc(100% - 80px);
  justify-content: center;
  overflow: auto;
}
.app .container .content {
  width: 300px;
  height:900px;
  background-color: yellow;
  color: black;
  margin:auto;
}
<div class="app">
  <header>Header</header>
  <div class="container">
    <div class="content">
      Variable content height
    </div>
  </div>
</div>

【讨论】:

  • 谢谢,这似乎有效。现在我必须尝试让它在我更复杂的场景中工作!
  • @Nuthinking 如果您遇到任何问题,可以回复我,但它应该适用于复杂的场景;)
猜你喜欢
  • 1970-01-01
  • 2016-11-16
  • 1970-01-01
  • 1970-01-01
  • 2012-11-23
  • 1970-01-01
  • 1970-01-01
  • 2019-05-04
  • 2023-03-09
相关资源
最近更新 更多