【问题标题】:How to prevent a flex item from stretching when wrapping [duplicate]包装时如何防止弹性项目拉伸[重复]
【发布时间】:2019-04-24 08:07:45
【问题描述】:

我正在尝试使用 flexbox 为我的应用程序创建一个网格系统。在 flex 容器上使用 flex-wrap: wrap 时遇到问题。

在下面的示例中,是否可以在不指定高度值的情况下防止我的标题向下拉伸一半?我希望标题与其中的内容一样高,而侧边栏和内容可以拉伸。

任何帮助将不胜感激。

html, body {
  height: 100%;
  margin: 0;
}
.container {
  display: flex;
  flex-wrap: wrap;
  height: 100%;
}
.cell1 {
  flex: 1 1 100%;
  background-color: #eee;
}
.cell2 {
  flex: 1 0 25%;
  background-color: #ddd;
}
.cell3 {
  flex: 1 0 75%;
  background-color: #ccc;
}
<div class="container">
  <div class="cell1">
    Header should be collapsed
  </div>
  <div class="cell2">
    Sidebar
  </div>
  <div class="cell3">
    Content
  </div>
</div>

【问题讨论】:

  • 使用align-content 控制包装的弹性行项目,由于它们水平“弹性”,您需要包装侧边栏/内容 并设置.container 流到column 能够实现您的要求。
  • 通过上面你可以将包装器设置为flex: 1,它将正确填充剩余的高度。

标签: html css flexbox frontend


【解决方案1】:

据我所知,align-self: flex-start 应该可以解决您的问题。将您的标头类 CSS 更新为:-

.cell1 {
  flex: 1 1 100%;
  background-color: #eee;
  align-self: flex-start;
}

【讨论】:

  • 这不会使 Sidebar/Content 填充剩余空间,因为 flex 行项目不会垂直“弯曲”。
【解决方案2】:

我认为应该是:

.container {
    display: flex;
    flex-wrap: wrap;
    height: 100%;
    align-items: flex-start;
}
.cell1 {
    flex: 1 1 100%;
    background-color: #eee;
    height: auto;
}
.cell2 {
    flex: 1 0 25%;
    background-color: #ddd;
    height: 100%;
}
.cell3 {
    flex: 1 0 75%;
    background-color: #ccc;
    height: 100%;
}

所以,只需确保将 height: auto 添加到标题中,将 height: 100% 添加到其余部分。这样,第一个元素将适合所有需要的实际高度,其余元素将伸展到容器。

【讨论】:

  • 不,这会使 Sidebar/Content 溢出其父级。要解决 OP 的问题,需要稍微更改标记。
  • 对我来说很好,这不是 OP 需要的吗? jsbin.com/xovediwudu/edit?html,css,output
  • 它添加了一个不应该存在的卷轴,如果你理解填充剩余空间(拉伸)的概念,你会发现你的解决方案没有工作。
  • 我明白了,谢谢。
猜你喜欢
  • 2016-02-26
  • 2018-12-12
  • 2017-09-07
  • 2019-06-20
  • 2018-10-08
  • 1970-01-01
  • 1970-01-01
  • 2021-10-31
  • 2010-09-20
相关资源
最近更新 更多