Search code examples
javascripthtmlcsscontenteditable

Caret position is way off in contenteditable div


Chrome (and maybe other browsers) position the caret in a strange way within a contenteditable div.

Please consider the following snippet:

<div contenteditable="true" style="width: 100%; height: 200px; border: 1px solid black; overflow: auto;">
    <p>
        <span contenteditable="false" style="width: 75%; height: 80px; display: inline-block; border: 1px solid red;">&nbsp;</span>.
    </p>
</div>

Also available in this JSFiddle.

If you click on the right-side of the period next to the red span and press backspace to delete the period, the caret suddenly shifts to the extreme right of the paragraph. I would expect the caret to be positioned where the period used to be, next to the red span.

Why is it not positioned the way I expect, and is there a way to get the behavior I'm looking for?


Solution

  • This strange behavior is happening because of the p tag, the cause is possibly some conflict between widths, you can edit the css of the tag, instead of using display:block(default), use display:inline.

    I created this fiddle: JsFiddle, with display:inline, was the closest I could get from the display:block.

    I tried the align attribute but I did not succeed.