【问题标题】:CSS: how to share remaining vertical space evenly?CSS:如何平均共享剩余的垂直空间?
【发布时间】:2015-08-06 08:52:36
【问题描述】:

我整个下午都在尝试实现一个相当简单的设计,首先使用 flex,然后只是使用旧的 div,但仍然卡住了。

HTML 布局相当简单。

<div id="interface">
  <div id="toolbar">
    Toolbar<br/>Toolbar
  </div>
  <div id="main">
    <div id="main-left">
      This should take the full vertical space remaining after the toolbar,
      and half the horizontal space.
    </div>
    <div id="main-right">
      <div id="context">
        This should take half and half the remaining space after the toolbar.
      </div>
      <div id="messages">
        This should take half and half the remaining space after the toolbar.
      </div>
    </div>
  </div>
</div>

问题是,我希望我的布局具有:

  • 不固定高度的顶部#toolbar

  • 屏幕的其余部分 #main 应垂直分割为 50%

    • 在左边,整个高度应该被#main-left占据

    • 右侧部分#main-right应该水平分割,两个部分(#context#messages)占据工具栏后剩余垂直空间的50%

以下小提琴的元素或多或少已经到位,但尺寸错误。

预期结果不应包含黄色。红色区域应该占据整个垂直空间。绿色和紫色应该占据垂直空间的一半。

不应该有顶级滚动条。如果任何红色、绿色、紫色的 div 内容太大,它应该会在自身内部溢出。

注意将#context#messages 的高度设置为50% 是不正确的,因为它们变得太大(看起来它们变成了#interface 高度的50%,而不是#main 的高度)

http://jsfiddle.net/59trW/63/

感谢您的帮助!

我愿意切换到弹性盒,但在那里遇到了类似的问题。

【问题讨论】:

    标签: css


    【解决方案1】:

    使用弹性盒,

    html, body, #interface {
      height: 100%;
      margin: 0;
    }
    #interface, #main, #main-right {
      display: flex; /* Flex container */
    }
    #interface, #main-right {
      flex-direction: column; /* Column layout */
    }
    #main, #main-left, #main-right, #context, #messages {
      flex: 1; /* Distribute space equally among the flex items */
      overflow: auto; /* Use scrollbars if necessary */
    }
    #toolbar    { background-color: pink;   }
    #main       { background-color: yellow; }
    #main-left  { background-color: red;    }
    #main-right { background-color: blue;   }
    #context    { background-color: green;  }
    #messages   { background-color: purple; }
    <div id="interface">
      <div id="toolbar">
        Toolbar<br/>Toolbar
      </div>
      <div id="main">
        <div id="main-left">
          This should take the full vertical space remaining after the toolbar,
          and half the horizontal space.
        </div>
        <div id="main-right">
          <div id="context">
            This should take half and half the remaining space after the toolbar.
          </div>
          <div id="messages">
            This should take half and half the remaining space after the toolbar.
          </div>
        </div>
      </div>
    </div>

    【讨论】:

    • 这几乎是完美的,除了右边的两个窗格没有占据 50% 的空间,而是与它们的内容成正比。我会在找出更好的解决方案时使用它。
    • @Ptival 我无法重现这种行为。根据规范,这不应该发生,所以这可能是您的浏览器的错误。
    • 确实在最新的 Chrome 和 Firefox 中行为是不同的。它在 Firefox 中按我想要的方式工作,并在 Chrome 下按比例进行。嗯……谢谢!
    • @Ptival 这是一个 Chrome 错误。 You can fix it adding flex-basis: 0
    猜你喜欢
    • 2014-06-16
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    相关资源
    最近更新 更多