代码之家  ›  专栏  ›  技术社区  ›  diwhyyyyy

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

  •  0
  • diwhyyyyy  · 技术社区  · 6 年前

    我有一些项目,我想安排在弹性框,以便他们将包装在较小的屏幕。 flex-wrap:wrap; 可以做到这一点。

    当它们被“打开”(即一个大屏幕)时,我希望在内容元素之间有一条垂直线。当屏幕/容器变窄时,我希望它们包装到下一行 有边界。

    我希望整件事都在这一页的中心。并不要求所有内容元素都具有相同的宽度。

    像这样的:

    enter image description here

    Smart borders between flex items – the dumb way ,但当flex box容器在页面中“浮动”时,这不起作用,因为它依赖隐藏的-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>
    0 回复  |  直到 6 年前
        1
  •  1
  •   Michael Benjamin William Falcon    6 年前

    要使用**flexbox*实现此行为,您需要一个媒体查询或其他一些触发器来删除wrap上的边框。所以除非你知道这些东西什么时候包装,否则这样的解决方案是没有帮助的。但这里有一个使用伪元素作为分隔符的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;”>食物棒食物棒食物棒食物棒食物棒食物棒</div>
    <div class=“item”style=“background color:grey;”gt;quux-quux-quux-quux-quux-quux</div>

    更多信息: https://stackoverflow.com/a/47887186/3597276