skip to Main Content

I’m trying to see if this is possible with flexbox. I’m trying to accomplish 2 things:

  1. Have div container width be 60% and another 40% (so only 2 items per row making 100%)
  2. Each row will reverse (so first row is 60%/40%, then next row would be 40%/60%)

My setup is as follows (The items will always be equal so in this case 6 items, a total of 3 rows)

.ImageContainer {
  display: flex;
  flex-wrap: wrap;
}

.ImageItem {
  border:1px solid #000000;
}

.ImageItem:nth-child(even) {
  width: 60%;
}

.ImageItem:nth-child(odd) {
  width: 40%;
}
<div class="ImageContainer">
  <div class="ImageItem">1</div>
  <div class="ImageItem">2</div>
  <div class="ImageItem">3</div>
  <div class="ImageItem">4</div>
  <div class="ImageItem">5</div>
  <div class="ImageItem">6</div>
</div>

2

Answers


  1. Try restructuring your code like this

    .ImageContainer {
      display: flex;
      flex-wrap: wrap;
    }
    
    .ImageRow {
      display: flex;
      flex: 1;
      width: 100%;
    }
    
    .ImageItem {
      flex: 1;
    }
    
    .ImageItem:nth-child(even) {
      flex: 60%;
    }
    
    .ImageItem:nth-child(odd) {
      flex: 40%;
    }
    <div class="ImageContainer">
      <div class="ImageRow">
        <div class="ImageItem"></div>
        <div class="ImageItem"></div>
      </div>
      <div class="ImageRow">
        <div class="ImageItem"></div>
        <div class="ImageItem"></div>
      </div>
      <div class="ImageRow">
        <div class="ImageItem"></div>
        <div class="ImageItem"></div>
      </div>
    </div>

    CSS does not have a parent selector or any way to target a previous sibling, that’s why you need to adjust your HTML code a bit, let me know if it helps in some way

    Login or Signup to reply.
  2. Use selectors as follows for the flex children. The ":nth-child(4n+x)" will select the children in steps of four with the corresponding "x" offset:

    html,
    body {
      margin: 0;
    }
    
    .ImageContainer {
      display: flex;
      flex-wrap: wrap;
      width: 100%;
    }
    
    .ImageItem {
      border: 1px solid #ccc;
      height: 60px;
      box-sizing: border-box;
    }
    
    .ImageItem:nth-child(4n+1),
    .ImageItem:nth-child(4n+4) {
      width: 60%;
    }
    
    .ImageItem:nth-child(4n+2),
    .ImageItem:nth-child(4n+3) {
      width: 40%;
    }
    <div class="ImageContainer">
      <div class="ImageItem"></div>
      <div class="ImageItem"></div>
      <div class="ImageItem"></div>
      <div class="ImageItem"></div>
      <div class="ImageItem"></div>
      <div class="ImageItem"></div>
      <div class="ImageItem"></div>
      <div class="ImageItem"></div>
      <div class="ImageItem"></div>
      <div class="ImageItem"></div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search