DEV Community

Cover image for Learn about content editable CSS attribute and how it is used to make editors for blogging websites in this post.
Saurabh Mhatre
Saurabh Mhatre

Posted on

4 3

Learn about content editable CSS attribute and how it is used to make editors for blogging websites in this post.

The contenteditable attribute specifies whether the content of an element is editable or not.
It is generally used to make rich text editors for blogging websites.
You can check out detailed video explanation of this tutorial here:-

Or follow along in this blog as well:-

We first add a contenteditable attribute to a div tag in HTML:-

<div class="editor-buttons">
  <a href="#" data-command="bold">
    <i class="fa fa-bold"></i>
  </a>
  <a href="#" data-command="italic">
    <i class="fa fa-italic"></i>
  </a>
</div>
<div contenteditable="true" class="editor">
  <p>Lorem ipsum dolor sit amet.</p>
</div>
Enter fullscreen mode Exit fullscreen mode

On third last line in the code above we have added content editable attribute with value set to true to allow our div tag to be editable.
Alt Text

Next we add support for fontawesome icons and add some css in our code:-

.editor {
  border: 1px solid lightgray;
  padding: 5px;
}

.editor-buttons {
  margin: 10px 0px;
}

a {
  color: black;
  border: 1px solid black;
  padding: 5px;
  margin: 0px 5px;
}
Enter fullscreen mode Exit fullscreen mode

Finally we use execCommand in Javascript to allow our editor to make text bold or italic:-

const links = document.querySelectorAll('a');

console.log("links",links);

links.forEach((link)=>{
  link.addEventListener("click",function(){
  const command = this.getAttribute('data-command');
  console.log(command);
  document.execCommand(command);
});
})
Enter fullscreen mode Exit fullscreen mode

You can learn more about execCommand here:-
W3Schools

Final codepen can be found here:-
https://codepen.io/codeclassifiers/pen/eYgBbeP

Content editable property is used widely in a lot of popular rich text editor libraries like Draft.js as well.
I hope this short explanation was useful for you all.

References:-
https://code.tutsplus.com/tutorials/create-a-wysiwyg-editor-with-the-contenteditable-attribute--cms-25657

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

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

Okay