← Back toHTML DOM

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

Written byPhuoc Nguyen
Level 2 — Intermediate
29 Feb, 2020
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
fakeEle.style.position = 'absolute';
fakeEle.style.top = '0';
fakeEle.style.left = '-9999px';
fakeEle.style.overflow = 'hidden';
fakeEle.style.visibility = 'hidden';
fakeEle.style.whiteSpace = 'nowrap';
fakeEle.style.height = '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
fakeEle.style.fontFamily = styles.fontFamily;
fakeEle.style.fontSize = styles.fontSize;
fakeEle.style.fontStyle = styles.fontStyle;
fakeEle.style.fontWeight = styles.fontWeight;
fakeEle.style.letterSpacing = styles.letterSpacing;
fakeEle.style.textTransform = styles.textTransform;

fakeEle.style.borderLeftWidth = styles.borderLeftWidth;
fakeEle.style.borderRightWidth = styles.borderRightWidth;
fakeEle.style.paddingLeft = styles.paddingLeft;
fakeEle.style.paddingRight = 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);
textboxEle.style.width = 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) {


See also

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn