Simple Cross-Browser Trick for Placeholders.

,
Looks like this article is pretty old. Some of the information and/or techniques may now be obselete. Just sayin’

When styling a form on a recent project I wanted to save space and hide field labels – using HTML5 placeholder attributes instead. But what about Internet Explorer? Here’s a simple cross-platform workaround I came up with.

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.

Let us help tell your story.

Ready to inject some karma into your project?

Get started