如何让一件物品在另一件物品开始收缩之前完全收缩?

hyp*_*ekt 6 html css flexbox

我试图创建一个随着视口变小而消失的边距,同时主要内容尽可能长时间地保持相同的大小。这个边距应该有一个最大尺寸,所以使用auto是不可能的。

换句话说,我的问题是如何控制网站上不同项目的收缩优先级。

Flexbox 模型允许设置收缩,但不能设置收缩顺序。

我必须使用哪些选项(不使用 Javascript)来实现此目的?

注意:我在这里回答我自己的问题,但我也在寻找更好的答案。

hyp*_*ekt 9

flex-shrink/flex-grow

一种方法是使用一个 Flexbox 项目flex-shrink,然后让另一个项目增长到它应有的大小flex-grow。这样,后一个项目将首先“收缩”(减少其增长)。

通过嵌套此结构可以实现两层以上。

.flex-container {
  display: flex;
}

.first-to-shrink {
  flex-shrink: 0;
  flex-grow: 1;
  flex-basis: 0px;
  min-width: 0px;
  background: coral;
}

.second-to-shrink {
  flex-shrink: 1;
  flex-grow: 0;
  background: cornflowerblue;
}
Run Code Online (Sandbox Code Playgroud)
<div class="flex-container">
  <div class="first-to-shrink flex-container">
    <div class="first-to-shrink">
      This is going to shrink first!
    </div>
    <div class="second-to-shrink">
      And then this one is going to shrink!
    </div>
  </div>
  <div class="second-to-shrink flex-container">
    <div class="first-to-shrink">
      This one is going next!
    </div>
    <div class="second-to-shrink">
      This is the last one to disappear!
    </div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

尺寸计算

另一种方法是计算每个项目的大小作为视口与在其之后应缩小的所有其他项目的大小之间的差异(这需要知道每个项目的大小),如下所示:

.shrinkable {
  overflow: hidden;
  max-height: 100px;
}

#first-to-shrink {
  height: calc(100vh - 300px);
  background: coral;
}

#second-to-shrink {
  height: calc(100vh - 200px);
  background: cornflowerblue;
}

#third-to-shrink {
  height: calc(100vh - 100px);
  background: coral;
}

#fourth-to-shrink {
  height: 100vh;
  background: cornflowerblue;
}
Run Code Online (Sandbox Code Playgroud)
<div id="first-to-shrink" class="shrinkable">
  This is going to shrink first!
</div>
<div id="second-to-shrink" class="shrinkable">
  And then this one is going to shrink!
</div>
<div id="third-to-shrink" class="shrinkable">
  This one is going next!
</div>
<div id="fourth-to-shrink" class="shrinkable">
  This is the last one to disappear!
</div>
Run Code Online (Sandbox Code Playgroud)