html - 如何显示 :flex container expand horizontally with its wrapped contents?

标签 html css flexbox

当使用 css flexbox 时,三种主要浏览器在某些方面的表现似乎完全不同。

在这种情况下,我尝试创建图像网格:

<div class="container">
     <div class="photo"></div>
     <div class="photo"></div>
     <div class="photo"></div>
     <div class="photo"></div>
     <div class="photo"></div>
     <div class="photo"></div>
</div>


.container {
    display:inline-flex;
    flex-flow : column wrap;
    align-content : flex-start;
    height : 100%;
}

在这个例子中,我需要一个容器,它本身包含几个 div 元素,设置为从上到下流动并在到达底部时换行。最终为我提供了照片列。

但是我需要容器水平扩展以容纳包裹的元素:

这是一个快速 jsFiddle进行演示。

行为如下:

  • IE 11 - 正确,容器水平拉伸(stretch)以包裹每列包裹元素
  • Firefox - 容器只包裹第一列元素,其余元素溢出。
  • Chrome - 容器总是拉伸(stretch)以填充其父级的宽度,无论它是什么。

在这种情况下,我想在其他两个浏览器中实现 IE11 的行为。因此我的问题是,如何使 flexbox 容器水平扩展以匹配其 column wrap 内容。

提前致谢。

最佳答案

奇怪的是,大多数浏览器都没有正确实现 column flex 容器,但对书写模式的支持相当不错。

因此,您可以使用垂直书写模式的行 flex 容器。这会将 block 方向与内联方向交换,因此 flex 元素将垂直流动。那么只需要恢复flex items内部的横写模式即可。

.container {
  display: inline-flex;
  writing-mode: vertical-lr;
  flex-wrap: wrap;
  align-content: flex-start;
  height: 350px;
  background: blue;
}
.photo {
  writing-mode: horizontal-tb;
  width: 150px;
  height: 100px;
  background: red;
  margin: 2px;
}
<div class="container">
  <div class="photo">1</div>
  <div class="photo">2</div>
  <div class="photo">3</div>
  <div class="photo">4</div>
  <div class="photo">5</div>
  <div class="photo">6</div>
  <div class="photo">7</div>
  <div class="photo">8</div>
  <div class="photo">9</div>
</div>

这种方法在边缘情况下可能有其自身的错误,特别是如果您混合使用 float 和嵌套 flexbox 等高级布局技术。但在大多数情况下,它似乎都能正常工作。

关于html - 如何显示 :flex container expand horizontally with its wrapped contents?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23408539/

相关文章:

polymer 1.0 : Where is documentation for <iron-flex-layout>?

javascript - 将 HTML 中的下拉列表与其他 HTML 页面链接

html - 减少 HTML 的大小但保持它看起来相似

javascript - <span> 光标未按预期工作

jquery - 使用 jQuery 将自定义属性添加到点 SVG 边缘

css - 想要使用 flexbox 在图像上叠加一个 div

html - 在电子邮件中嵌入音乐播放器

javascript - 如何仅在单击 div 时使按钮可见

javascript - 无法同时运行两个javascript函数

html - 网站布局 : Shall I use CSS-width with percentage or flexbox?