Search code examples
csshtmlcontenteditable

Styling an inline element with linebreak (after) within a content editable element - caret position


I'm styling an inline element within a contenteditable element to visually represent a linebreak.

First text(Linebreak)
[C]Second Line

I want to be able to place the cursor at [C] position which I'm unable to. I believe there's a reasonable explanation for the current behavior. Anyone care to explain and maybe provide me a different approach?

EDIT: Apparently it works for IE and Firefox but not Chrome.

.lb{
  display:inline;
}

.lb:after{
  content: "\21B2\A";
  white-space: pre;
  word-wrap: break-word;
}
.edit-box{
  border: 1px solid black;
  padding: 10px;
}
<div id="test" contenteditable="true" class="edit-box">
  How to style the span element<span class="lb"></span>so it's possible to place the cursor at the beginning of this line, before "S".
</div>


Solution

  • Try the follow css changes in your lb classes with addition of .lb:before:

    .lb{
      display:inline;
      white-space: nowrap;
    }
    
    .lb:before{
      content:'';
      display:block;
    }
    
    .lb:after{
      content: "\21B2\A";
    }
    

    This will achieve what you want. What we are doing is that we are telling the main lb to not wrap the text in and around it. Next we create lb before as block to get it into new line and then a lb after to add the cursor and the rest of the text flows along with it. Hope this helps.