为什么字体大小会增加输入的宽度

Flo*_*elt 7 html css flexbox

我想知道为什么font-size在 HTML 上设置CSS 属性会input自动增加其宽度?

我明白为什么它会增加高度,但我希望input在更改font-size.

我问的原因是因为它破坏了我正在构建的 flex 布局,其中有一个input. 当我增加字体大小时,input完全脱离了布局。

这是一个(反应)再现:

<div
  style={{
    backgroundColor: 'blue',
    display: 'flex',
    flexDirection: 'column',
    maxWidth: 400,
    padding: 20,
    alignItems: 'center',
  }}
>
  <div style={{ display: 'flex' }}>
    <span>Some text</span>
    <input style={{ 'font-size': 20 }} />{' '}
  </div>

  <div style={{ display: 'flex' }}>
    <span>Some text</span>
    <input style={{ 'font-size': 50 }} />
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

有没有干净的方法来解决这个问题?

Sti*_*ers 7

<input>标签是被替换的元素之一,它们通常具有内在尺寸。

在 flexbox 中,您可以通过添加以下内容来覆盖固有大小:

input {
  min-width: 0;
}
Run Code Online (Sandbox Code Playgroud)

或者,给它一个小于size默认值的值20

<input size="1">
Run Code Online (Sandbox Code Playgroud)

然后使用flex/ flex-grow/flex-basiswidth根据需要设置所需大小。


Kur*_*tis 3

您可以在输入上使用 100% 宽度或固定宽度。另外,要使其在 IE 中工作,您需要alignItems: 'center'从最外层的 div 中删除

<div
    style={{
        display: 'flex',
        flexDirection: 'column',
        maxWidth: 400,
        padding: 20,
    }}
>
    <div style={{ display: 'flex' }}>
        <span>Some text</span>
        <input style={{ 'font-size': 20, width: "100%", boxSizing: "border-box" }} />
    </div>

    <div style={{ display: 'flex' }}>
        <span>Some text</span>
        <input style={{ 'font-size': 50, width: "100%", boxSizing: "border-box" }} />
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

对于 Firefox,您必须将输入包装在容器中并应用于flex: 1 1 auto;该容器。

希望有帮助