Search code examples
htmlcsscontenteditable

Overlapping contenteditable spans


Some contenteditable boxes overlap others as such not all boxes are editable. I want to preserve the text aligned to the center at the position of the spans as below. How do I achieve this?

span {
  margin: auto;       
	text-align: center;
	width: 100%;
}
<span contenteditable style="position:absolute; top: 26.8%; left:41%">●</span>
<span contenteditable style="position:absolute; top: 36.6%; left:41%">●</span>
<span contenteditable style="position:absolute; top: 46.4%; left:41%">●</span>
<span contenteditable style="position:absolute; top: 56.2%; left:41%">●</span>
<span contenteditable style="position:absolute; top: 26.8%; left:24%">●</span>
<span contenteditable style="position:absolute; top: 36.6%; left:24%">●</span>
<span contenteditable style="position:absolute; top: 46.4%; left:24%">●</span>
<span contenteditable style="position:absolute; top: 56.2%; left:24%">●</span>
<span contenteditable style="position:absolute; top: 26.8%; left:75%">●</span>
<span contenteditable style="position:absolute; top: 36.6%; left:75%">●</span>
<span contenteditable style="position:absolute; top: 46.4%; left:75%">●</span>
<span contenteditable style="position:absolute; top: 56.2%; left:75%">●</span>


Solution

  • I came up with a solution using jquery to reposition and keep it centered:

    $('[contenteditable]').on('focus', function() {
        var $this = $(this);
        $this.data('before', $this.html());
        $this.data('leftbefore', $this.offset().left + ($this.width()/2));
        return $this;
    }).on('blur keyup paste', function() {
        var $this = $(this);
        if ($this.data('before') !== $this.html()) {
            $this.data('before', $this.html());
            $this.trigger('change');
            $this.offset({ left:($this.data('leftbefore') - ($this.width() / 2))});
        }
        return $this;
    });
    

    if someone has a better solution, please do tell