DEV Community

Cover image for Add placeholder text to div with contenteditable="true"
Axorax
Axorax

Posted on

7 4 4 4 4

Add placeholder text to div with contenteditable="true"

You may have come across the contenteditable attribute. It's used in many places. It's a much better alternative to something like a textarea. You can add contenteditable="true" to any div and then it acts like an input field. In this article, I will show you how to add placeholder to text to it as it doesn't support the placeholder attribute right out of the box.

The code needed

div[contenteditable] {
  &[placeholder]:empty::before {
    content: attr(placeholder);
    z-index: 9;
    line-height: 1.7;
    color: #555;
    word-break: break-all;
    user-select: none;
  }

  &[placeholder]:empty:focus::before {
    content: "";
  }
}
Enter fullscreen mode Exit fullscreen mode

That's all the code you need! However, if you only add that to the CSS then it won't work. You need to add a placeholder attribute to your HTML and also ensure that the div is visible.

Full code / Example

HTML

<div contenteditable="true" placeholder="Subscribe to Axorax on YT! :D"></div>
Enter fullscreen mode Exit fullscreen mode

CSS

div[contenteditable] {
  /* Basic styles */
  width: 20rem;
  height: 15rem;
  padding: 1rem;
  background: #292929;
  color: #fff;

  /* Placeholder code */
  &[placeholder]:empty::before {
    content: attr(placeholder);
    z-index: 9;
    line-height: 1.7;
    color: #555;
    word-break: break-all;
    user-select: none;
  }

  &[placeholder]:empty:focus::before {
    content: "";
  }
}
Enter fullscreen mode Exit fullscreen mode

Preview Image

That's all there is to it. Hope you find it useful!

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay