【问题标题】:max-width used for flex container instead of fit-content用于 flex 容器的 max-width 而不是 fit-content
【发布时间】:2023-01-16 19:34:19
【问题描述】:

如果您运行下面的代码 sn-p,您可以看到用于顶部 <div> 的宽度是 200px (max-width)。但实际上它不需要使用 max-width 因为最后一个 <p> 被包装了。相反,想要的结果是使用底部 <div> 使用的宽度 (~140px)。

我怎样才能使用首选宽度并仍然让项目包装?

div {
  max-width: 200px;
  width: fit-content;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  background-color: green;
  margin-bottom: 8px;
}

p {
  background-color: red;
}
<div>
  <p>
    test
  </p>
  <p>
    this is a long text
  </p>
  <p>
    short text
  </p>
</div>

<div>
  <p>
    test
  </p>
  <p>
    longer text
  </p>
</div>

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    如果我对问题的理解是正确的,您可以通过在 p 元素上使用 flex-basis 而不是在 div 上使用 max-width 来实现:

    div {
      min-width: 140px;
      width: fit-content;
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      background-color: green;
      margin-bottom: 8px;
    }
    
    p {
      flex-basis: auto;
      background-color: red;
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-29
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 2018-12-10
      • 2015-08-22
      • 2018-07-19
      • 2022-01-04
      • 1970-01-01
      相关资源
      最近更新 更多