【问题标题】:split space of a fixed size container equally. a case for flexbox?等分固定大小容器的空间。 flexbox 的案例?
【发布时间】:2016-09-01 05:14:25
【问题描述】:

如何设计 HTML/CSS 结构,将固定大小的容器水平分成三部分。第一部分应该与内容需要一样高。第二部分和第三部分将共享剩余的空间 550——不管它们的内容如何。如果其内容的大小超过此限制,则该部分应该是可滚动的。

其中的 HTML 部分很简单:一个 div 容器,其中包含三个 div 作为子级。

我尝试使用 flexbox 解决这个问题 - 但是可能有更好的选择:

css部分:

#container {
  position: absolute;
  width: 100%; height: 100%;
  display: flex;
  flex-direction: column;
}

#item1 { flex: 0 0 auto; }
#item2 { flex: 1 1 auto; }
#item3 { flex: 1 1 auto; }

不幸的是,这仅在第 2 项或第 3 项的内容不太大时才有效。

有关问题的更详细实现,请参阅this fiddle

body {
  margin: 0;
  overflow: hidden;
}
* {
  box-sizing: border-box;
}
#container {
  position: absolute;
  width: 100%;
  height: 100%;
  border: 2px solid green;
  display: flex;
  flex-direction: column;
}
#item1 {
  flex: 0 0 auto;
  background-color: Bisque;
}
#item2 {
  flex: 1 1 auto;
  background-color: DarkOrange;
}
#item3 {
  flex: 1 1 auto;
  background-color: MediumAquaMarine;
}
<div id="container">
  <div id="item1">I'll be as tall as my content takes.</div>
  <div id="item2">From the rest, I'll take exactly 50%. No matter how short or long my content is. If needed there should be scrollbars.</div>
  <div id="item3">I'll take the other 50% of the rest!
    <br>right?
    <br>right?
    <br>right?
    <br>right?
    <br>right?
    <br>right?
    <br>right?
    <br>right?
    <br>right?
    <br>right?
    <br>right?
    <br>right?
    <br>right?
    <br>right?
    <br>right?
    <br>right?
    <br>right?
    <br>right?
    <br>right?
    <br>right?
    <br>right?
    <br>right?
    <br>right?
  </div>
</div>

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    是的,您可以使用 flex。这是您的代码的一些改进。 Item1 不需要有弹性规则,item2 和 item3 将有flex: 1

    我还添加了overflow-y: auto; 规则以使其可滚动。

    Example

    #item1 {background-color: Bisque ; }
    #item2 { flex: 1; background-color: DarkOrange ; overflow-y: auto;}
    #item3 { flex: 1; background-color: MediumAquaMarine ; overflow-y: auto;}
    

    【讨论】:

    • 很好,这行得通。所以“0 0 auto”似乎是默认值。看起来关键部分是其他“自动”属性。我猜 flex: 1 1 还等于 flex: 1 。谢谢。
    • 奖励:如果 item2 和 3 之间的比例可以通过鼠标调整大小,该怎么办。微不足道的补充还是:另一个帖子?
    • 听起来像另一个帖子 :)
    猜你喜欢
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 2017-05-09
    • 2017-01-12
    相关资源
    最近更新 更多