Simple Cross-Browser Trick for Placeholders

Ian Ebden · January 3, 2013

Looks like this article was written a while ago. Some of the ideas and/or techniques described may now be obselete.

The placeholder attribute specifies a “short hint that describes the expected value of an input field (e.g. a sample value or a short description of the expected format). The hint is displayed in the input field when it is empty, and disappears when the field gets focus.”

It’s pretty widely supported except in Internet Explorer and older browsers. Two minutes searching on Google turns up some good cross-browser workarounds (including this one), which would’ve been fine since I was already using Modernizr. However I like to try and solve problems by writing less code rather than more, so I wondered if there was a simpler, more graceful solution.

Modernizr to the rescue

If you’re not familiar with Modernizr, it’s a Javascript library that runs on page load to detect supported CSS features, and adds classes to your html tag for you to key your CSS on. It’s perfect for progressively enhancing a website based on a browser’s capability.

In this case we’re looking for HTML (placeholder) support rather than CSS, but we could use Modernizr to detect more generally whether we’re dealing with a modern browser – e.g. one that supports new features like CSS transitions. We can then assume that if the browser supports CSS transitions it will also support the placeholder attribute – which, to the best of my knowledge is correct at time of writing. So now we have a cross-browser solution that requires no extra scripting, just a couple of extra lines of CSS:

.csstransitions label {
	display: none;

Mark up your form – labels and all – and let Modernizr do the rest. Modernizr will add the .csstransitions class for modern browsers, which will then hide the labels. Internet Explorer and older browsers will still show your labels. Future versions of Internet Explorer are likely to support CSS transitions and placeholder, so everyone is happy.