Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<br> is inserted into contenteditable html element if left empty

Tags:

html

I have a <div contenteditable="true"></div> and when I enter some content into it, then delete these content, it seems like the browser is inserting a <br> element automatically into this element.

Does anyone has any experience with this? Know how to fix it?

like image 327
Tri Nguyen Avatar asked Feb 01 '13 02:02

Tri Nguyen


People also ask

What does Contenteditable do in HTML?

The contenteditable attribute specifies whether the content of an element is editable or not. Note: When the contenteditable attribute is not set on an element, the element will inherit it from its parent.

How do I make Contenteditable in HTML?

You can set the HTML5 contenteditable attribute with the value true (i.e. contentEditable="true" ) to make an element editable in HTML, such as <div> or <p> element.

How do I stop Enter key in Contenteditable?

To prevent contenteditable element from adding div on pressing enter with Chrome and JavaScript, we can listen for the keydown event on the contenteditable element and prevent the default behavior when Enter is pressed. to add a contenteditable div. document. addEventListener("keydown", (event) => { if (event.

What is false about Contenteditable attribute?

contenteditable="false" Indicates that the element is not editable. contenteditable="inherit" Indicates that the element is editable if its immediate parent element is editable.


1 Answers

Use SPAN element as your contenteditable element instead of DIV element.

Please read complete. Q. Why the idea works? A. Span is an inline element and Div is a block element. Block elements when empty, by default, will have zero dimensions(if no padding is applied to the block element). In contrast, empty inline elements tend to maintain their height and width becomes zero. Hence, we just need to provide proper width to this Span(or any inline element), but, an inline element won't take width as a property and therefore we need to specify the display of this inline element as inline-block or block.

I have extensively used this idea for creating online-editors. Hope this helps.

NOTE: On changing display of an inline element to block/inline-block, doesn't mean the nature of element has changed. It is still an inline element, so an inline element will never be able to hold a block element inside it.

like image 103
Shyam Swaroop Avatar answered Sep 20 '22 16:09

Shyam Swaroop