nicholas79171 nicholas79171 - 1 month ago 13
CSS Question

How do I prevent the contenteditable tag from being inherited in child elements?

I have a simple

<div contenteditable>
with a
<span>
inside of it. The text inside of the
<div>
I want to be editable, but the
<span>
I do not want users to be able to edit.

Sample:



#editable {
background-color: #ccc;
padding: 5px;
width: 400px;
text-align: center;
}

span {
background-color: green;
color: white;
padding: 2px;

}

<div id="editable" contenteditable>
Sample text including a <span>FANCY TAG</span> in the middle.
</div>





The desired end result is a box where users can type in what they'd like, but have styled tags inline that are not editable. Since you cannot put
<span>
tags inside of
<input type="text">
or
<textarea>
blocks, I'm left with using
<div contenteditable>
.

How do I make all the text inside the
<div>
editable except for the
<span>
?

Answer

Add contenteditable="false" to your span tag thus this prevents user from editing your span tag.

#editable {
  background-color: #ccc;
  padding: 5px;
  width: 400px;
  text-align: center;
}

span {
  background-color: green;
  color: white;
  padding: 2px;
  
}
 
<div id="editable" contenteditable>
  Sample text including a <span contenteditable="false">FANCY TAG</span> in the middle.
</div>

Comments