How can I create this alternating layout?

前端 未结 3 1750
太阳男子
太阳男子 2020-12-22 14:46

This is the HTML I need to use:

相关标签:
3条回答
  • 2020-12-22 14:49

    You can try something like this. Your pattern is repeating each 4 elements so you need to consider nth-child(4n + x):

    .images {
      display:flex;
      min-height:100vh;
      flex-wrap:wrap;
      align-content:flex-start;
    }
    .image {
      height:50px;
      border:1px solid;
      box-sizing:border-box;
    }
    
    .image:nth-child(4n+1),
    .image:nth-child(4n+4) {
       width:40%;
       background:red;
    }
    
    .image:nth-child(4n+2),
    .image:nth-child(4n+3) {
       width:60%;
       background:blue;
    }
    <div class="images">
      <div class="image"></div>
      <div class="image"></div>
      <div class="image"></div>
      <div class="image"></div>
      <div class="image"></div>
      <div class="image"></div>
      <div class="image"></div>
      <div class="image"></div>
    </div>

    0 讨论(0)
  • 2020-12-22 14:57

    .images .odd {
        float:left;
    }
    .images .even {
        float:right;
    }
    <div class="images">
      <div class="image odd"></div>
      <div class="image even"></div>
      <div class="image odd"></div>
    </div>

    0 讨论(0)
  • 2020-12-22 15:04

    You can in fact simplify the CSS from the accepted answer:

    .images {
      display:flex;
      min-height:100vh;
      flex-wrap:wrap;
      align-content:flex-start;
    }
    .image {
      height:50px;
      border:1px solid;
      box-sizing:border-box;
      width:60%;
      background:blue;
    }
    
    .image:nth-child(4n),
    .image:nth-child(4n+1) {
       width:40%;
       background:red;
    }
    <div class="images">
      <div class="image"></div>
      <div class="image"></div>
      <div class="image"></div>
      <div class="image"></div>
      <div class="image"></div>
      <div class="image"></div>
      <div class="image"></div>
      <div class="image"></div>
    </div>

    0 讨论(0)
提交回复
热议问题