Skip to content Skip to sidebar Skip to footer

How Can I Create This Alternating Layout?

This is the HTML I need to use:

Solution 1:

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;
}
<divclass="images"><divclass="image"></div><divclass="image"></div><divclass="image"></div><divclass="image"></div><divclass="image"></div><divclass="image"></div><divclass="image"></div><divclass="image"></div></div>

Solution 2:

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;
}
<divclass="images"><divclass="image"></div><divclass="image"></div><divclass="image"></div><divclass="image"></div><divclass="image"></div><divclass="image"></div><divclass="image"></div><divclass="image"></div></div>

Solution 3:

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

Post a Comment for "How Can I Create This Alternating Layout?"