Skip to main content

HTML5 Placeholder with style

Published on 23rd March 2013

Since the start of the year I have used the placeholder attribute in a couple of new site builds. Used in the correct way it can add a nice design touch to your web forms.

So what is it?

HTML5 brings many improvements to web forms. One of them is the placeholder attribute. This allows you to set placeholder text inside an input field. The text is displayed until the field is focused upon (clicked on) and then disappears when you start typing. It works in all modern browsers and a polyfill (fallback) can be used for older browsers. Before the placeholder attribute, javascript was used to fake placeholder text within the input field.

The markup

<input type="text" name="name" id="name" placeholder="Name">

view demo

The polyfill for older browsers

There is a great javascript polyfill for the placeholder attribute. It's lightweight at only 4kb and has zero dependencies.

Styling the placeholder attribute

After using the placeholder text, I came across the problem of how to style it. I wanted to change the colour of the placeholder text to fit in with the overall site colour scheme. Luckily I found a great stack overflow post explaining how to do do it with pseudo-elements and pseudo-classes.

/* WebKit */
::-webkit-input-placeholder { 
  color: #b2424b;
}
/* Mozilla Firefox 4 to 18 */
:-moz-placeholder { 
  color: #b2424b;
}
/* Mozilla Firefox 19+ */
::-moz-placeholder { 
  color: #b2424b;
}
/* ie 10+ */
:-ms-input-placeholder { 
  color: #b2424b;
}

There are two important points from the article: -

  1. IE up to version 9 and Opera up to version 12 do not support any CSS selector for placeholders. (They will still show on older IE browsers with the polyfill but css styles will be ignored)
  2. Must be separate rules for each browser. Otherwise the whole group would be ignored by all browsers.

view demo