Changing the Colour of Placeholder Text

Hero image for Changing the Colour of Placeholder Text. Image by Kelly Sikkema.
Hero image for 'Changing the Colour of Placeholder Text.' Image by Kelly Sikkema.

The placeholder attribute in HTML allows you to specify placeholder text for an input field. This text is displayed inside the input field when it is empty, and it disappears when the field is focused or a value is entered.

By default, the placeholder text is styled using the user agent's default styles, which may vary depending on the browser, operating system, and user preferences. However, you can use CSS to customize the appearance of the placeholder text very easily using the ::placeholder pseudoelement.

For example, this will change the colour of the placeholder text in any input field on the page to blue:

input::placeholder {  color: blue;}

You can of course combine this with more specific selectors (like classes or IDs) if you wish to target particular elements. For example:

.my-input::placeholder {  color: red;}#my-input::placeholder {  color: red;}

Or using Sass, it could look something not too dissimilar to:

.my-input {  // general input styles  color: red;    &::placeholder {    // styles specifically applied when in 'placeholder' state    color: blue;  }}

You can also combine this with using CSS variables to define the colour of the placeholder text, which can make it easier to maintain and update the styles of your application:

:root {  --placeholder-color: blue;}input::placeholder {  color: var(--placeholder-color);}

Whilst support is generally extremely good, you do need to bear in mind that the CSS ::placeholder pseudoelement is not supported in Internet Explorer. So, if you are using placeholder styling in a missioncritical way, and IE is still on your browser support matrix, then you may need to look into using a polyfill or an alternative approach (such as showing and hiding an overlaid span to replicate the same behaviour).


The Wrap‑Up

In conclusion, you can use CSS to customize the appearance of placeholder text in input fields. By using the ::placeholder pseudoelement and defining the desired styles, you can change the colour (and many other style attributes) of the placeholder text to match the design of your application.


Categories:

  1. Accessibility
  2. CSS
  3. Front‑End Development