【CSS】flex配合margin实现元素均匀分布

现有代码如下,要求不使用网格布局,根据剩余空间设置margin

<div className="container">
  {
    
    Array.from({
    
     length: 12 }, (_, i) => i).map((item) => (
    <div className="box">{
    
    item}</div>
  ))}
</div>
.container {
    
    
  width: 300px;
  height: 200px;
  display: flex;
  flex-wrap: wrap;
  border: 1px solid #ccc;
  background-color: #efefef;

  .box {
    
    
    width: 50px;
    height: 50px;
    border-radius: 6px;
    background-color: #bfd;
  }
}

效果如下

在这里插入图片描述

实现

.container {
    
    
  margin: 50px;
  width: 300px;
  height: auto;
  display: flex;
  flex-wrap: wrap;
  border: 1px solid #ccc;
  background-color: #efefef;

  .box {
    
    
    --n: 5;
    --rest: calc(100% - 50px * var(--n));
    margin: 10px calc(var(--rest) / var(--n) / 2);
    width: 50px;
    height: 50px;
    border-radius: 6px;
    background-color: #bfd;
  }
}

猜你喜欢

转载自blog.csdn.net/owo_ovo/article/details/142763799