代码之家  ›  专栏  ›  技术社区  ›  Pete Irfan TahirKheli

弹性砖石效果包装不当

  •  0
  • Pete Irfan TahirKheli  · 技术社区  · 6 年前

    我尝试使用flex实现以下布局,但似乎无法实现:

    * {
      box-sizing: border-box;
    }
    
    .box {
      border: 1px solid black;
      width: 50%;
      padding-top: 25%;
      float: left;
    }
    
    .box:first-child {
      padding-top: 50%;
    }
    
    .box:nth-last-child(-n+2) {
      width: 25%;
    }
    <div class="wrapper">
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
    </div>

    如果我尝试使用“弯曲方向”行,它将最后两个框包装在第一个左框下面

    * {
      box-sizing: border-box;
    }
    
    .wrapper {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
    }
    
    .box {
      border: 1px solid black;
      width: 50%;
      padding-top: 25%;
    }
    
    .box:first-child {
      padding-top: 50%;
    }
    
    .box:nth-last-child(-n+2) {
      width: 25%;
    }
    <DIV class=“wrapper”>
    <DIV class=“box”></DIV>
    <DIV class=“box”></DIV>
    <DIV class=“box”></DIV>
    <DIV class=“box”></DIV>
    &L/DIV & GT;

    如果我使用“弯曲方向”列,我会靠近一点,但必须设置一个高度,这意味着我会失去响应能力。

    * {
      box-sizing: border-box;
    }
    
    .wrapper {
      display: flex;
      flex-direction: column;
      flex-wrap: wrap;
      height:400px;
      width:100%;
    }
    
    .box {
      border: 1px solid black;
      width: 50%;
      padding-top: 25%;
    }
    
    .box:first-child {
      padding-top: 50%;
    }
    
    .box:nth-last-child(-n+2) {
      width: 25%;
    }
    <DIV class=“wrapper”>
    <DIV class=“box”></DIV>
    <DIV class=“box”></DIV>
    <DIV class=“box”></DIV>
    <DIV class=“box”></DIV>
    &L/DIV & GT;

    有没有一种方法可以在没有固定高度或改变HTML结构的情况下使用flex来实现这种布局?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Temani Afif    6 年前

    使用flexbox可以考虑 乱劈 估计这个。一个技巧是有两行(保持行方向),并在第一个元素上使用负的边距,使其与第二行重叠:

    * {
      box-sizing: border-box;
    }
    
    .wrapper {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
    }
    
    .box {
      outline: 1px solid black;
      width: 50%;
      padding-top: 25%;
    }
    
    .box:first-child {
      padding-top: 25%;
      margin-bottom:-25%;
    }
    
    .box:nth-last-child(-n+2) {
      width: 25%;
    }
    .box:nth-child(3) {
      margin-left:auto;
    }
    <div class="wrapper">
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
    </div>