How to disable an input field using CSS?

Have you ever thought that you can disable an input field using pure CSS? Well, it’s quite easy task and we can achieve this with a little CSS code.

The simplest way to disable an input field using CSS is to apply the pointer-events: none; on the input element that you want to disable. It will restrict the visitors to click on this input element and will make it read-only.

Here is a working example:

Example:

input[type="text"]{
   pointer-events: none;
}

The above method only works until you use the tab key to navigate between input fields. But, If you use a tab key to navigate between the input fields, your browser will let you type in text in that input field.

So, the question is how can you prevent that?

Well, to restrict the user with the tab key, you have to add an attribute tabindex="-1" to the input field. Something like this:

<input type="text" placeholder="Enter your name" tabindex="-1">

Now, if you apply pointer-events: none; on the input element, it will restrict the user either ways clicking on this input and the input element will work as a read-only field.

Here is the modified version of the above example:

Example:

input[type="text"]{
   pointer-events: none;
}

Note: The pointer-events property lets you control the user mouse event on HTML elements.

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.