Guide: HTML5 Placeholder Attribute: Quick Guide

One of my favorite new pieces in HTML5 is the ability to add something Placeholder text easy. The text placeholder is the gray text found in an input field that is used to give users a hint as to what input is expected in that field. Once users start typing in the input field, this text disappears. We used to do this often with JavaScript, as follows;

There is nothing wrong with this practice, but it is easier on HTML5. HTML5 introduced a new attribute with a logical name; placeholder. Here’s an example:

If we look at it in the browsers, the input should now have the gray text as seen below; A few things to note: According to the specification, the placeholder attribute should not be used as an alternative to a label, and it is also recommended to apply this attribute only to input types that require text, e.g. Text, password, search, email, text box and tel. Add placeholder to the input types: radio and checkbox makes no difference.

Placeholder and CSS

Additionally, formatting the placeholder text via CSS is also possible, but at the time of writing this is still limited to Firefox and Webkit browsers only. The following example shows how we change the placeholder text to green, both in Webkit and Firefox; input :: – webkit-input-placeholder {color: green;} input: -moz-placeholder {color: green;}

However, keep in mind that the :: – webkit-input-placeholder and: -moz-placeholder will only affect the text and cannot be written in parallel. input :: – webkit-input-placeholder, input: -moz-placeholder {color: green;} This piece of code will not work. CSS3 also came to support this feature with the introduction of the [placeholder] attribute selector; imports[placeholder] {border: 1px solid green;} In the example above, we select each entry that has the placeholder attribute and change the border to green.

Browser compatibility

These new HTML5 feature unsurprisingly, it is not supported in old browsers and is currently only fully supported in: Firefox 4+, Chrome 4+, Safari 5+, Opera 11.6 and Internet Explorer 10 (which has not yet been officially released). However, if we need to display the placeholder in older browsers, but can still use the placeholder attribute, we can use Polyfills. There are many Placeholder Polyfills beyond that, but in this example we’re going to use the PlaceMe.js;

HTML5 Placeholder Attribute  Quick Guide 2021  2022  - 73HTML5 Placeholder Attribute  Quick Guide 2021  2022  - 75HTML5 Placeholder Attribute  Quick Guide 2021  2022  - 84HTML5 Placeholder Attribute  Quick Guide 2021  2022  - 34HTML5 Placeholder Attribute  Quick Guide 2021  2022  - 79HTML5 Placeholder Attribute  Quick Guide 2021  2022  - 99