Styling placeholder texts

A quick note on styling placeholder texts. Although it’s very easy, it turns out that both MDN and the usual go-to CSS Tricks article leave out one important bit of data: when setting the color you should add opacity: 1 for Firefox.

Unstyled

My task was to make sure that text in input fields, including placeholder text, uses exactly the same font and text colour as regular text.

Here is the unstyled test; first a reference paragraph, then a form field with a value, then a form field with a placeholder. As you see the form fields use their own font, and not the one I use on this site.

The quick brown fox jumped over the lazy dog.

Solution

We set font: inherit on all inputs (and textareas, while you’re at it), and the fonts show up right. Easy, no?

Setting the text colour is equally simple, even though we have to use three proprietary pseudo-elements (see below). I use inherit here as well, but of course you can use any colour you like.

That gives the following effect. Fonts and colours are right — except in Firefox, where the placeholder text remains greyed out.

The quick brown fox jumped over the lazy dog.

opacity

At first I thought Firefox doesn’t support color for placeholder texts, but a few Twitter followers demonstrated that that was not the case. Turns out Firefox needs just one more thing: opacity: 1.

The default style of placeholders is greyed-out text. Apparently Firefox achieves it by setting opacity, while the other browsers use color. There’s nothing wrong with either, but it should be documented.

The quick brown fox jumped over the lazy dog.

So these are the full styles, with the three necessary pseudo-elements. Note the finicky syntax; the -webkit- and -moz- flavours MUST have :: while IE MUST have : (though Edge accepts both). Personally I still find the whole :: thing a bit silly, but who am I to judge? (Regular readers will know I judge anyway.)

input {
	font: inherit;
}

::-webkit-input-placeholder {
	color: inherit;
}

::-moz-placeholder {
	color: inherit;
	opacity: 1;
}

:-ms-input-placeholder {  
	color: inherit;
}

Now everything works fine. It would be useful if documentation sites, especially Mozilla’s own, added the opacity detail; it would have saved me an hour of work today (15 minutes solving the problem and 45 minutes writing this article).

This is the blog of Peter-Paul Koch, web developer, consultant, and trainer. You can also follow him on Twitter or Mastodon.
Atom RSS

If you like this blog, why not donate a little bit of money to help me pay my bills?

Categories: