How to Set Width of an input Element using HTML & CSS?

In this article, we will discuss how we can set the width of an input element using HTML & CSS.

To set the width of the input element, we can use any of the following methods:

You can use either of the two methods to set the input width. Each method is simple and easy to use. Let’s discuss each one in detail.


Set the Width of an input Element using HTML size Attribute

HTML’s size attribute allows you to set the width of input elements in characters.

For example, if you set size="10", it means that the input element would be 10 characters wide.

Here is a live example:

Example:

<label>Enter Your Name:</label>
<input type="text" size="10">

<br><br>

<label>Enter Your Name:</label>
<input type="text" size="20">

Although the above approach is very easy to use and does what we need. Still, We recommend you not to use it as it might cause some unexpected results.

This is because the size attribute specifies the width of the input element in typed characters. Therefore, the width of the input element will be dependent on the size and style of the fonts being used.

This means if you set the size=”10″ for two input elements and both inputs have different font-size, the input with a higher value of font-size will have larger width although both inputs have the same value of the size attribute.

Here is an example which shows the difference:

Example:

.input1{
   font-size: 20px;
}
.input2{
   font-size: 30px;
}

Set the Width of an input Element using CSS width Property

In the previous approach, we have seen that the size attribute is not efficient to set the width of the input element as it is dependent on the size and style of the fonts being used.

We can overcome this problem with CSS width property.

CSS width property lets you specify the width of input elements in various CSS units such as px, em, rem, etc. Also, it is not dependent on the size of the fonts.

The below example set the width of the input elements in px:

Example:

.input1{
   width: 100px;
}
.input2{
    width: 200px;
}

If you want to apply the same width to multiple inputs, you can use CSS attribute selectors to select the desired ones.

Here is an example which sets a 200px width of each text input:

Example:

input[type="text"]{
   width: 200px;
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.