Using CSS :placeholder-shown to Customize Styles for Empty Text Input

css
Published on September 27, 2019

Use-Cases of this Tutorial

  • Know how to give specific CSS to <input> and <textarea> elements currently showing placeholder text.
  • Know how to give specific CSS to empty text input without Javascript involved.
  • Know about the :placeholder-shown CSS.

It is commonly required to give a different look to empty <input> / <textarea> elements so that is becomes clear to the user that they need to fill them.

Previously it would have required a bit of Javascript to do this. But now it can be done using only CSS, taking help of the newly introduced :placeholder-shown pseudo-class.

:placeholder-shown is a selector for <input> / <textarea> elements who are currently showing placeholder text — which means they are basically empty. Once the user fills the textbox (so that placeholder text would not be seen) the specific CSS styles won't be applied.

/* show black color border when non-empty */
input {
	border: 1px solid black;
}

/* show red color border when placeholder text is seen (when empty) */
input:placeholder-shown {
	border: 1px solid red;
}

Any CSS property suited for <input> / <textarea> elements can be used in :placeholder-shown as well.

Demo

A common design pattern implemented in forms is to highlight text fields that are empty. Fields that are not mandatory to be filled are not required to be highlighted. Such a design can be achieved with :placeholder-shown as shown below.

HTML :

<div id="demo-container">
	<div>
		<label>Name *</label>
		<input type="text" name="name" class="required-field" placeholder="Name" />
	</div>
	<div>
		<label>Email *</label>
		<input type="text" name="email" class="required-field" placeholder="Email" />
	</div>
	<div>
		<label>Address</label>
		<input type="text" name="address" placeholder="Address" />
	</div>
</div>

CSS :

#demo-container input {
	border: 2px solid #cccccc;
}

#demo-container input.required-field:placeholder-shown {
	border: 2px solid #686de0;
}
In this Tutorial