以每行有 3 个子元素的方式包装 flex 子元素

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

这是一个 flex 容器,flex-direction as row with flex-wrap。我需要以这样的方式包装它,即当屏幕尺寸 <1616 时,每一行总是有 3 个子元素。

这是代码。顺便说一句,我正在使用 Tailwind CSS,但欢迎您使用简单 CSS 的答案:

    <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>

此处 flex 容器的宽度太宽,这就是第四个元素附加在第一行的原因。 当屏幕尺寸为 1616px 时,父 flex 容器的宽度为 866px。所以我尝试为 flex 容器设置 max-width [866px];但是运气不好:(

当父级为 display:flex 时,您可以使用 flex-basis 属性 指定宽度。一般我们用的shorthand叫flex。它为您提供了一些额外的选项来指定 flex-item 如何与其他项目成比例地增长或缩小。 flex: flex-grow flex-shrink flex-basis;。因此,对于您的情况,SingleProductCard 包装器组件添加 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 class="flex-container">
  <div class="flex-item-1">1</div>
  <div class="flex-item-2">2</div>
  <div class="flex-item-3">3</div>
  <div class="flex-item-4">4</div>
</div>
</body>