【问题标题】:Flex items are stretching [duplicate]Flex项目正在拉伸[重复]
【发布时间】:2022-01-12 13:19:45
【问题描述】:

如何避免 flex 列中的项目拉伸到全宽?我希望它是创建时的原始大小。

.myForm {
  display: flex;
  flex-direction: column;
}
<form class="myForm">
  <input type="text" />
  <input type="text" />
  <button>Test</button>
</form>

【问题讨论】:

  • 正确的输入和按钮没有给定宽度。给它们一些宽度。

标签: html css


【解决方案1】:

在子元素上使用max-width: max-content;width: max-content;

.myForm {
  display: flex;
  flex-direction: column;
}
/* below will be select any first level children under .myForm */
.myForm > * {
    max-width: max-content;
}
<form class="myForm">
  <input type="text" />
  <input type="text" />
  <button>Test</button>
</form>

【讨论】:

    【解决方案2】:

    CSS 中,flex 属性align-items 的默认值是stretch,正如您猜想的那样,它会将 flex 父级的子级拉伸到全宽。你可以改变它来解决这个问题。比如

    .myForm {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
    }
    <form class="myForm">
      <input type="text" />
      <input type="text" />
      <button>Test</button>
    </form>

    在此处阅读有关此属性的更多信息https://developer.mozilla.org/en-US/docs/Web/CSS/align-items

    【讨论】:

    • 您的回答效果很好,但与我的方法不同。因此,请不要编辑与我的答案无关的内容。我会为你投票,因为它是工作和 100% 弹性 CSS。
    • 我知道对不起,我试图编辑我的,结果不知何故编辑了你的
    • 没问题 :-) 我也搞错了。
    【解决方案3】:

    你提到了 display:flex;因此您的元素大小也可以调整为列大小。 您可以为您的第一级孩子单独提供 css 属性,例如

    .myForm > * {
        width: fit-content;
    }
    

    .myForm {
      display: flex;
      flex-direction: column;
    }
    /* below will be select any first level children under .myForm */
    .myForm > * {
        width: fit-content;
    }
    <form class="myForm">
      <input type="text" />
      <input type="text" />
      <button>Test</button>
    </form>

    【讨论】:

      猜你喜欢
      • 2021-05-09
      • 2018-02-17
      • 2021-03-18
      • 2021-10-31
      • 1970-01-01
      • 2012-10-19
      • 2014-12-29
      • 2019-11-21
      • 2015-10-16
      相关资源
      最近更新 更多