HTML inputs use a “placeholder” attribute for temporary text that vanishes once typing begins.
I’m talking about this:
An HTML example:
<input type="text" placeholder="Enter your full name">
Code language: HTML, XML (xml)
To make this work, browsers apply specific styles to the placeholder text by default, which is usually a shade of grey for the font color. You can change the styles of the placeholder in all modern browsers using the ::placeholder
pseudo-element.
You could, for instance, do this:
input::placeholder {
font-style: italic;
font-size: 0.8em;
color: #888;
opacity: 0.8;
}
Code language: CSS (css)
Notice you’re able to style just about anything. These aren’t necessarily recommended styles, but they demonstrate what’s possible. To be more specific, what you can style this way are:
color
font-style
font-weight
text-decoration
letter-spacing
line-height
text-transform
text-shadow
opacity
With one added trick, you can also style the background of the element. For that, plus when you want to style the input when its placeholder is visible (rather than the text itself), you can use the :placeholder-shown
pseudo-class. For example:
input:placeholder-shown {
border: 2px solid #0CAFFA;
background: #f1f1f1;
}
Code language: CSS (css)
This will add a nice little blue border around your input plus a light grey background. Again, keep in mind that this specific code above will only take effect on the field when its placeholder is visible. When the user inputs anything, the styles will be disabled – or rather will revert to whatever was set for the input element itself.
Does this work everywhere?
Short answer, yes.
Back in the day, you had to include additional rules for WebKit, old Firefox and IE syntax. For example, through lines like:
::-webkit-input-placeholder {/* ... */}
:-moz-placeholder {/* ... */}
::-moz-placeholder {/* ... */}
:-ms-input-placeholder {/* ... */}
::input-placeholder {/* ... */}
::placeholder {/* ... */}
Code language: CSS (css)
Nowadays, though, none of it is required. Modern browsers all support the standard ::placeholder
pseudo-element out the gate.
💡 Good practice: use the element-qualified selector for clarity.
You might have noticed that in the first code example above, I use: input::placeholder
rather than simply ::placeholder
. The latter would also work, but it’s not considered a good practice any more.
Using an element-qualified selector lets you be explicit about which elements you intend to style.
Here is a complete demo that shows an example implementation of custom-styled placeholder text in CSS and HTML:
WPShout has been delivering weekly tutorials, reviews, and deep dives for WordPress developers and business owners since 2009. To maintain our independence and continue creating high-quality content, we increasingly rely on donations from our community.
Donate today to support independent technical publishing.
…
Don’t forget to join our crash course on speeding up your WordPress site. Learn more below: