"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Add placeholder text to div with contenteditable=\"true\"

Add placeholder text to div with contenteditable=\"true\"

Published on 2024-07-29
Browse:844

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: "";
  }
}

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

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: "";
  }
}

Add placeholder text to div with contenteditable=\

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

Release Statement This article is reproduced at: https://dev.to/axorax/add-placeholder-text-to-div-with-contenteditabletrue-aa6?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3