Search code examples
htmlcontenteditableword-wrap

How can a contenteditable div not break words on non-whitespace and behave as a normal div?


I have a case where users input text into a contenteditable div and the result is later displayed in a normal div. The input div has a max-width set to allow text to wrap to new lines.

The issue is that the text is displayed differently in the input vs the output. The input seems to break inside of words whereas the output lets the text overflow and only breaks in whitespace. Is it possible to get the same behavior in the input?

See this fiddle for an example: https://jsfiddle.net/s1m40m2p/1/

html

<body>
  <div contenteditable="true" id="input-div" class="both-divs"></div>
  <div id="output-div"  class="both-divs"></div>
</body>

css

.both-divs {
  min-height : 20px;
  max-width: 100px;
  font-size: 16px;
  font-family: monospace;
  overflow: visible;
}

#input-div {
  outline: 1px solid red;
}

#output-div {
  outline: 1px solid blue;
}

js

const inputElt = document.getElementById('input-div')
const outputElt = document.getElementById('output-div')
inputElt.addEventListener('input', () => {
  outputElt.innerText = inputElt.innerText;
})

output

Bottom is the desired behavior for the top.


Solution

  • try and add overflow-wrap:normal in #input-div {` your problem will be solved

    const inputElt = document.getElementById('input-div')
    const outputElt = document.getElementById('output-div')
    inputElt.addEventListener('input', () => {
    	outputElt.innerText = inputElt.innerText;
    })
    .both-divs {
      min-height : 20px;
      max-width: 100px;
      font-size: 16px;
      font-family: monospace;
      overflow: visible;
    }
    
    #input-div {
      outline: 1px solid red;
    overflow-wrap:normal;
    }
    
    #output-div {
      outline: 1px solid blue;
    }
    <html>
    <body>
    
    <div contenteditable="true" id="input-div" class="both-divs">
    
    </div>
    <div id="output-div"  class="both-divs">
    </div>
    </body>
    </html>

    enter image description here