マイペースなRailsおじさん

Ruby、Ruby on Rails、オブジェクト指向設計を主なテーマとして扱います。だんだん大きくなっていくRuby on Rails製プロダクトのメンテナンス性を損なわない方法を考えたり考えなかったりしている人のブログです。

Set placeholder for 'contenteditable' element.

We can add placeholder to contenteditable element.

HTML

[contenteditable="true"]:empty::before {
    content: attr(data-placeholder);
    color: #ccc;
}

CSS

<p contenteditable="true" data-placeholder="Please input something."></p>

And then we placeholder appers. f:id:ytnk531:20210217054622p:plain

Sample

https://jsfiddle.net/ytnk531/tgLw1fv5/5/

We user empty selector to match empty input element. And use attr(data-placeholder) to write placeholder content.

Notice: Element should be empty

Definition of empty is shown in here. We can not have whitespaces inside contenteditable element.

<!- Empty ->
<p contenteditable="true" data-placeholder="Please input something."></p>
<p contenteditable="true" data-placeholder="Please input something."><!- Comments are OK. -></p>
<!- Not Empty ->
<p contenteditable="true" data-placeholder="Please input something.">
</p>
<p contenteditable="true" data-placeholder="Please input something."> </p>

When using some editors, be careful to automatically inserted whitespaces.