Set width of an input text box in HTML, CSS, and JavaScript
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.
|
1 2 3 4 5 6 |
<html> <body> <label for="name">Enter a value:</label> <input type="text" id="name" style="width: 200px;"> </body> </html> |
Alternatively, you can also use the size attribute to define the width of the <input>.
|
1 2 3 4 5 6 |
<html> <body> <label for="name">Enter a value:</label> <input type="text" id="name" size="20"> </body> </html> |
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
|
1 2 3 4 5 6 |
<html> <body> <label for="name">Enter a value:</label> <input type="text" id="name" class="someclass"> </body> </html> |
CSS
|
1 2 3 |
.someclass { width: 200px; } |
Alternatively, you can also use the CSS selector of an input text box for setting the width CSS property.
HTML
|
1 2 3 4 5 6 |
<html> <body> <label for="name">Enter a value:</label> <input type="text" id="name"> </body> </html> |
CSS
|
1 2 3 |
input[type="text"] { width: 200px; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
<html> <body> <form> <label for="name">Enter a value:</label> <input type="text" id="name"> </form> </body> <script> document.getElementById("name").setAttribute('size', '20'); </script> </html> |
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
|
1 2 3 4 5 |
$(document).ready(function() { $('#name').keyup(function() { $(this).attr('size', $(this).val().length) }); }); |
HTML
|
1 2 3 4 |
<form> <label for="name">Enter a value:</label> <input type="text" id="name"> </form> |
That’s all about setting the width of an input text box in HTML, CSS, and JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)