AbstractBrain Answers About us →

How to create a label inside an input with HTML and CSS

Question

How can I create a label inside an input?

I would like to add a gray text inside an input field that disappears when the user clicks on the field and starts typing.

Do I need JavaScript or I can simply use HTML / CSS? What is the easiest solution?

It would also be useful if the solution works also on textarea.

Answer

The easiest way to create a label inside an input with HTML5 is to use the placeholder field:

<input type="text" placeholder="My label">

The text of the placeholder is displayed in light gray and when the user clicks on the field and starts typing the help text disappears automatically. The help text also appears again if the field becomes empty.

This is much easier and more accessible than using JavaScript for that.

Note that you can also change the style of the placeholder with CSS:

::placeholder {
  color: red;
}