I'm wondering why setting the font-size
CSS attribute on an HTML input
automatically increases its width?
I understand why it increases the height, but I'd like an input
to remain the same base width when changing the font-size
.
The reason I ask, is because it is breaking a flex layout I'm building, in which there is an input
. When I increase the font-size, the input
completely breaks out of the layout.
Here's a (react) reproduction:
<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>
Is there a clean way to solve this?
The inputfields are not effected by font variations you make for the bodyelement. You have to style them separately. To change that, use input[type=text] { font-size: inherit; } Share Follow
3 It's because the inputalready have font-sizedefined by the user agent unlike pelement so the pelement will inheritthe value defined by the bodyand inputwill use its own value unless you override it: So the input element will have the computed value of font-sizelike follow:
Font Size. The font-size property sets the size of the text. Being able to manage the text size is important in web design. However, you should not use font size adjustments to make paragraphs look like headings, or headings look like paragraphs.
And although you have to be careful when making generalised statements about font size, it can be said that fonts with large x-heights compared to the cap height tend to appear larger than fonts where the x-height is relatively small. Each font has a specific ratio between cap height and x-height which also affects the general legibility of a font.
<input>
tag is one of the replaced elements and they often have intrinsic dimensions.
In flexbox you can override the intrinsic size by adding:
input {
min-width: 0;
}
Or, give it a smaller size
than the default value 20
:
<input size="1">
Then set the desire size by using flex
/ flex-grow
/ flex-basis
, or width
as needed.
You can use 100% width or a fixed width on the inputs. Also to get this working in IE, you need to remove alignItems: 'center'
from the outer most 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>
For firefox you have to wrap the input in a container and apply flex: 1 1 auto;
to the container.
Hope that helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With