展开的弹性盒项目之间的垂直边界

Vertical border between unwrapped flex-box items

我有一些项目想在 flex-box 中排列,以便它们可以在较小的屏幕上换行。 flex-wrap:wrap; 可以做到这一点。

当它们是 "unwrapped"(即宽屏幕)时,我希望内容元素之间有一条垂直线。当 screen/container 变窄时,我希望它们换到下一行并且 没有 有边框。

我希望整个内容都位于页面中央。不需要所有内容元素都具有相同的宽度。

像这样:

我见过 Smart borders between flex items – the dumb way,但是当页面中的 flex-box 容器是 "floating" 时,这不起作用,因为它依赖于隐藏的 -1px 边距来隐藏备用边框,这意味着项目必须一直延伸到左边距以隐藏它们的边距。对于居中的盒子,这并不总是正确的。

/* Based on https://codepen.io/thatemil/pen/MrrJyZ 
 * used by
 * https://thatemil.com/blog/2018/01/08/direction-independent-borders-this-is-stupid/
 */
.container {
  display: flex;
  flex-wrap: wrap;
  overflow: hidden;
  justify-content: center;
}

.item {
  border-left: 1px solid red;
  margin-left: -1px;
  padding: 5px;
}
Short (unwrapped):

<div class="container">
  <div class="item" style="background-color:pink;">foobar</div>
  <div class="item" style="background-color:grey;">quux</div>
</div>

Long (wrapping):

<div class="container">
  <div class="item" style="background-color:pink;">foobar foobar foobar foobar foobar foobar</div>
  <div class="item" style="background-color:grey;">quux quux quux quux quux quux quux</div>
</div>

要使用 **flexbox* 实现此行为,您需要媒体查询或其他一些触发器来删除环绕边框。因此,除非您知道物品何时包装,否则这样的解决方案没有帮助。但是这里有一个使用伪元素作为分隔符的 flex 容器的演示。

jsFiddle demo

.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.item {
  padding: 5px;
}

.item:first-child {
  order: 1;
}

.item:last-child {
  order: 3;
}

.container::before {
  order: 2;
  content: "";
  border-right: 2px solid red;
}
<div class="container">
  <div class="item" style="background-color:pink;">foobar foobar foobar foobar foobar foobar</div>
  <div class="item" style="background-color:grey;">quux quux quux quux quux quux quux</div>
</div>


另一个可能的选项是 CSS 网格 。使用容器的背景颜色和 grid-column-gap 属性 作为分隔符,使用 auto-fit 函数进行包装。

jsFiddle demo

.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  background-color: red;
  grid-column-gap: 2px;
}

.item {
  padding: 5px;
}
<div class="container">
  <div class="item" style="background-color:pink;">foobar foobar foobar foobar foobar foobar</div>
  <div class="item" style="background-color:grey;">quux quux quux quux quux quux quux</div>
</div>

更多信息: