Home > front end >  Need a responsive solution for wrapping 3 list items per row
Need a responsive solution for wrapping 3 list items per row

Time:04-09

A separate question to find the final solution which we almost have found enter image description here

And this is an illustration to clarify what should happen if we have 4 or more items in the list: enter image description here

And this is the code I tried (thanks for the help in the other post):

.parent{
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  height: 100px;
  gap: 20px;  
  box-sizing: border-box;
  justify-content: space-between;
  background-color: lightgreen;
}
.child{
  flex-basis: 30%;
  background-color: blue;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div >
  <div > <span>1</span> </div>
  <div > <span>2</span> </div>
  <div > <span>3</span> </div>
  <div > <span>4</span> </div>
  <div > <span>5</span> </div> 
</div>

CodePudding user response:

Use :after pseudo element to simulate an invisible child div so the alignment of the items is fixed to left. And media queries for the responsive. Check the snippet to get some idea.

.parent {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  height: 100%;
  gap: 20px;
  box-sizing: border-box;
  justify-content: space-between;
  background-color: lightgreen;
}

.parent::after {
  content: "";
  width: 30%;
  height: 0;
}

.child {
  flex-basis: 30%;
  background-color: blue;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
}

@media only screen and (max-width : 1024px) {
  /* for tablet */
  .parent::after {
    width: 46%;
  }
  .child {
    flex-basis: 46%;
  }
}

@media only screen and (max-width : 768px) {
  /* for mobile */
  .parent::after {
    display: none;
  }
  .child {
    flex-basis: 100%;
  }
}
<div >
  <div > <span>1</span> </div>
  <div > <span>2</span> </div>
  <div > <span>3</span> </div>
  <div > <span>4</span> </div>
  <div > <span>5</span> </div>
</div>

  • Related