Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the width of an input HTML element so that it matches the size of its content?

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 :

  • I will get more and more whitespace if I type only some "l" characters
  • the size will be insufficient if I type only some "w" characters

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).

like image 403
JB Hurteaux Avatar asked May 31 '12 12:05

JB Hurteaux


People also ask

How do you make an input field the same size in HTML?

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.

How do you measure width in HTML?

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.

How do you find the content width?

The clientWidth property is used to get the width of its element. This value will represent the width of text in pixels.

How do you write input to width?

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.


1 Answers

You could use a (hidden) canvas and the measureText() method of the context to get your string's width.

EDIT:

Looks fast enough.

like image 86
dda Avatar answered Oct 02 '22 07:10

dda