This post will discuss how to set the width of an input text box in HTML, CSS, and JavaScript.

1. Set width in HTML

In HTML, you can use the width attribute to set the width of an element.

Edit in JSFiddle

 
Alternatively, you can also use the size attribute to define the width of the <input>.

Edit in JSFiddle

2. Set width with CSS

It is good practice to separate CSS from HTML markup. The idea is to define a class to set the width CSS property.

HTML


CSS



Edit in JSFiddle

 
Alternatively, you can also use the CSS selector of an input text box for setting the width CSS property.

HTML


CSS



Edit in JSFiddle

3. Set width with JavaScript

With JavaScript, you can use the setAttribute() method to set the value of the size attribute on the input text box.

Edit in JSFiddle

 
You can also dynamically change the width of a text box to match the length of the input. We can easily do this by setting the size attribute on key events.

JS


HTML



Edit in JSFiddle

That’s all about setting the width of an input text box in HTML, CSS, and JavaScript.