How to calculate the width of an input HTML element so that it matches the size of its content ? I already update an input on the fly as the user types :
<input type='text' onkeydown='this.size=this.value.length' />
However, this does not seem completely correct because it does not take into account the fact that some characters are longer than others :
How to proceed?
PS: Why I want to do this (already answered this in a answer that was deleted)? I have sentences in which I have to replace the bracket content by inputs (ex: [user] is [years] old). I have no idea what the sentence can be, so I do not know an adequate length for the inputs, and I would like to keep it readable on one line (avoiding too much whitespace).
To create the inputs of the same width, we have to use some CSS attributes in our program. box-sizing: It defines how the height and width of the element are calculated. moz-box-sizing: It is supported in the Mozilla Firefox browser only. -webkit-box-sizing: It is supported in the Google Chrome browser only.
If you need to know the total amount of space an element occupies, including the width of the visible content, scrollbars (if any), padding, and border, you want to use the HTMLElement. offsetWidth and HTMLElement. offsetHeight properties.
The clientWidth property is used to get the width of its element. This value will represent the width of text in pixels.
The width attribute specifies the width of the <input> element. Note: The width attribute is used only with <input type="image"> . Tip: Always specify both the height and width attributes for images. If height and width are set, the space required for the image is reserved when the page is loaded.
You could use a (hidden) canvas and the measureText()
method of the context to get your string's width.
EDIT:
Looks fast enough.
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