Home > Blockchain >  Wrap flex child element in a way that each row has 3 child elements
Wrap flex child element in a way that each row has 3 child elements

Time:04-12

enter image description here

This is a flex container with flex-direction as row with flex-wrap. I need to wrap it in such a way that each row always has 3 child elements when the screen size<1616.

Here is the code. Btw I am using Tailwind CSS, but your answers with plain CSS are welcomed:

    <div className='flex flex-wrap flex-row gap-6 mb-12 '>
      <SingleProductCard/>
      <SingleProductCard/>
      <SingleProductCard/>
      <SingleProductCard/>
      <SingleProductCard/>
      <SingleProductCard/>
    </div>

SingleProductCard.js

    <div className='single-product w-[250px] h-[510px] rounded-lg border border-[#D1D1D1] lg:w-[200px]'>
    <div className="product-image bg-primary w-[210px]   h-[150px] my-2 rounded-lg m-auto lg:w-[175px]"></div>
    
    <p className='text-sm pb-2 pl-2 font-semibold mt-4'>Product Title</p>
    <p className='text-xs pb-4 text-[#575757] pl-2'>Small space for product description</p>
    
    <div className="flex justify-between mb-4">
    <p className='text-sm font-[600] mt-[6px] pl-2'>2.46$</p>
    <button className='text-sm  py-1 px-4  bg-[#6A983C] text-white rounded-md mr-4'>Buy</button>
    </div>

  </div>

Here the width of the flex container is too wide and that is why the fourth element appends in the first row. When the screen size is 1616px the parent flex container width is 866px. So I tried setting max-width [866px] for the flex container; But no luck :(

CodePudding user response:

When parent is display:flex you can specify the width using flex-basis property. Generally we use the shorthand called flex. It gives you some additional options to specify how the flex-item can grow or shrink proportional to other items. flex: flex-grow flex-shrink flex-basis;. So, for your case SingleProductCard wrapper component add flex: 0 1 33%.

* {
  box-sizing: border-box;
}
body{
    width: 100vw;
}
.flex-container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  font-size: 30px;
  text-align: center;
}
@media (max-width: 1616px) {
  .flex-item-1, .flex-item-2, .flex-item-3, .flex-item-4{
    padding: 10px;
    flex: 0 1 33%; /* to all flex-items */
  }
}
.flex-item-1 {
  background-color: cornflowerblue;
}

.flex-item-2 {
  background-color: dodgerblue;
  
}
.flex-item-3 {
  background-color: crimson;
}
.flex-item-4 {
  background-color: forestgreen;
}
<body>
<div >
  <div >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
</div>
</body>

  • Related