柔性间隙和柔性包裹百分比

Víc*_*rro 6 html css flexbox

我正在构建一个表单,其中字段的宽度百分比由客户端动态设置。我的第一个方法是创建一个启用了换行的 Flex 容器,并使用gap: 16px. 令我惊讶的是,flex-wrap它的gap表现并不像我想象的那样。

main {
  width: 400px;
  background-color: gray;
  
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

div {
  background-color: blue;
}

.first {
  width: 50%;
}

.second {
  width: 50%;
}
Run Code Online (Sandbox Code Playgroud)
<main>
  <div class="first">First</div>
  <div class="second">Second</div>
</main>
Run Code Online (Sandbox Code Playgroud)

我预计他们会在同一条线上,并且中间有差距。当我删除flex-wrap.

我发现的唯一解决方案是使用calc(50% - 16px),但这远非理想。也许我错误地处理了这个问题?

小智 2

这篇文章有答案。 https://wiryawanadipa.com/blog/calculate-percentage-width-of-flex-items-when-using-gap/

解决方案是基于每行项目数量和间隙大小的公式:

宽度: calc((100% / n) - (((n - 1) / n) * g));

其中 [n = 每行的项目数] 和 [g = 间隙大小]

:root {
    --flex-gap: 1rem; /* Variable for gap */
}

*,
*::after,
*::before {
    box-sizing: border-box;
}
.container {
  display: flex;
  flex-wrap: wrap;
  gap: var(--flex-gap);
}
.item {
  --flex-items: 1; /* Variable for number of items */
  width: calc((100% / var(--flex-items)) - (((var(--flex-items) - 1) / var(--flex-items)) * var(--flex-gap)));
  padding: 3rem 1rem;
  background-color: #999;
  color: white;
  font-size: 28px;
  text-align: center;
}
@media (min-width: 520px) {
  .item {
    --flex-items: 2; /* Variable for number of items */
  }
}
@media (min-width: 768px) {
  .item {
    --flex-items: 3; /* Variable for number of items */
  }
}
@media (min-width: 1200px) {
  .item {
    --flex-items: 4; /* Variable for number of items */
  }
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
  <div class="item">6</div>
  <div class="item">7</div>
  <div class="item">8</div>
</div>
Run Code Online (Sandbox Code Playgroud)