Resize the width of a text box to fit its content automatically

Let's say that an input has the id of textbox as below:

<input type="text" id="textbox" />

To adjust its width based on its content dynamically, we create a fake element whose content is the same as the input value. And we set the input's width as the fake element's width.

// Create a div element
const fakeEle = document.createElement('div');

// Hide it completely = 'absolute'; = '0'; = '-9999px'; = 'hidden'; = 'hidden'; = 'nowrap'; = '0';

// We copy some styles from the textbox that effect the width
const textboxEle = document.getElementById('textbox');

// Get the styles
const styles = window.getComputedStyle(textboxEle);

// Copy font styles from the textbox = styles.fontFamily; = styles.fontSize; = styles.fontStyle; = styles.fontWeight; = styles.letterSpacing; = styles.textTransform; = styles.borderLeftWidth; = styles.borderRightWidth; = styles.paddingLeft; = styles.paddingRight;

// Append the fake element to `body`

The function below sets the HTML for the fake element, calculates its width and sets the result to the original input.

const setWidth = function() {
const string = textboxEle.value ||
textboxEle.getAttribute('placeholder') || '';
fakeEle.innerHTML = string.replace(/\s/g, '&' + 'nbsp;');

const fakeEleStyles = window.getComputedStyle(fakeEle); = fakeEleStyles.width;

This post introduces more ways to measure the width of given text in given font

Finally, we invoke the setWidth function when users change the input value by listening on the input event:


textboxEle.addEventListener('input', function(e) {



Resize an image
Scroll an element to ensure it is visible in a scrollable container