Enabling Placeholders in ContentEditable Elements with CSS

HTML5, CSS3 and JavaScript

The Fine Art of Web Development by Martin Ivanov

Recently I worked on an HTML5 app, utilizing contenteditable elements. According to the specs of the app, the empty editable elements were supposed to have placeholder texts and since the placeholder attribute is only supported by standard input boxes and textareas I was planning to use JavaScript to enable this functionality in contenteditable elements, but then I decided to try this small CSS trick with generated content and the attr(attribute) function, which actually worked:

The CSS:

[sourcecode language=”css”][contenteditable]:empty::before
{
content: attr(data-placeholder);
font-style: italic;
opacity: .75;
}[/sourcecode]

… And the Markup:

[sourcecode language=”css”]<div contenteditable data-placeholder="Add some text…"></div>[/sourcecode]

If you are interested in more CSS3, HTML5 WebComponents and JavaScript stuff, make sure you check my experiments website.

Categories and Tags
Links

© 2006 - 2018 Martin Ivanov