缩小以适应 flexbox 或 flex-basis 中的内容:内容解决方法?

Shrink to fit content in flexbox, or flex-basis: content workaround?

我有一个网络应用程序,我正在使用 flexbox 进行布局。

我正在尝试填满屏幕(这是一个应用程序,而不是文档),并尽可能不指定任何固定的宽度或高度,因为内容可能是各种各样的东西(完整的流体布局!梦想!)

所以我需要流畅的高度,全宽的页眉和页脚,然后中间的主面板填充剩余的垂直 space,分为几列,当太高时每列滚动,而每个非主列的宽度应缩小以适合其内容,主列用完剩余的 space.

我非常接近,但不得不求助于显式调整非主列的大小 - 我相信 flex-basis: content; 应该这样做,但浏览器尚不支持。

这里是 minimal demo 显示固定大小的列:

var list = document.querySelector('ul')

for (var i = 0; i < 100; i++) {
  var li = document.createElement('li')
  li.textContent = i
  list.appendChild(li)
}
html,
body {
  height: 100%;
  width: 100%;
  margin: 0;
}
body {
  display: flex;
  flex-direction: column;
}
main {
  display: flex;
  flex-direction: row;
  overflow: hidden;
}
main > section {
  overflow-y: auto;
  flex-basis: 10em;
  /* Would be better if it were fluid width/shrink to fit, unsupported: */
  /* flex-basis: content; */
}
main > section:last-child {
  display: flex;
  flex: auto;
  flex-direction: column;
}
main > section:last-child > textarea {
  flex: auto;
}
<header>
  <h1>Heading</h1>
</header>

<main>
  <section>
    <h1>One</h1>
    <ul>
    </ul>
  </section>

  <section>
    <h1>Two</h1>
  </section>

  <section>
    <header>
      <h1>Three</h1>
    </header>
    <textarea></textarea>
    <footer>
      <p>Footer</p>
    </footer>
  </section>
</main>

<footer>
  <p>Footer</p>
</footer>

看起来像这样 - 我希望列 OneTwo 到 shrink/grow 适合而不是固定:

我的问题是,flex-basis: content 是否有仅 CSS 的解决方法,或者实现此目标的替代方法?

我可能可以像上面那样固定列大小,或者使用 javascript,但我有一个该死的梦想。

I want columns One and Two to shrink/grow to fit rather than being fixed.

你试过了吗:flex-basis: auto

或者这个:

flex: 1 1 auto,是

的缩写
  • flex-grow: 1(按比例增长)
  • flex-shrink: 1(按比例缩小)
  • flex-basis: auto(初始大小基于内容大小)

或者这个:

main > section:first-child {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:nth-child(2) {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:last-child {
    flex: 20 1 auto;
    display: flex;
    flex-direction: column;  
}

revised demo

相关:

事实证明它正在正确地收缩和生长,一直提供所需的行为;除了在所有当前的浏览器中 flexbox 没有考虑垂直滚动条!这就是内容似乎被切断的原因。

你可以在这里看到,这是我在添加固定宽度之前使用的原始代码,看起来列没有增长以容纳文本:

http://jsfiddle.net/2w157dyL/1/

但是,如果您将该列中的内容加宽,您会发现它总是将其截断相同的量,即滚动条的宽度。

所以修复非常非常简单 - 添加足够的右填充以考虑滚动条:

http://jsfiddle.net/2w157dyL/2/

  main > section {
    overflow-y: auto;
    padding-right: 2em;
  }

我是在尝试 Michael_B 建议的一些事情(特别是添加填充缓冲区)时发现的,非常感谢!

编辑:我看到他也发布了一个 fiddle 做同样的事情 - 再次非常感谢你的帮助