Search code examples
javascriptcsstextword-wrap

wrap span's extra text to next line


I'm trying to wrap the extra text to the next line using overflow-wrap: break-word but the problem is when you click, span moves down to next line then the extra text breaks on that next line.

I want the yellow text 'BlaBla:' to be on the same line as the text 'sometextssomet...', however I want the 'sometextssomet...' text to have the overflow-wrap: break-word; applied to it inside of the <p> element.

What am I doing wrong?

document.addEventListener('mousedown', () => {

  let name = document.createElement("p");
  name.className = 'Name'
  name.innerHTML = 'BlaBla: '
  name.style = `height:40px; color: #f4c41f`

  document.getElementsByClassName('main')[0].appendChild(name)

  let text = document.createElement("span");
  text.innerHTML = `sometextssometextssometextssometextssometexts`
  text.style = `overflow-wrap: break-word; font-size:14px; color: #ffffff; background: none; `

  document.getElementsByClassName('Name')[0].appendChild(text)
})
.main {
  position: relative;
  width: 250px;
  height: 140px;
  overflow-wrap: break-word;
  background-color: gray;
}
<div class="main" id="main0"></div>


Solution

  • If I understand your question, then there are a few things here to change. First, the <p> has a margin applied to it by default, which is causing this vertical "jump" that you are noticing when it's added to your document. Try adding the following CSS to address this issue:

    p {
        margin-top:0;
    }
    

    Also, consider adding a <span> to the created <p> for both the yellow "blabla" text, and the white text to allow the break-word CSS rule to work as required by doing the following:

    document.addEventListener('mousedown', () => {
      
      // Create span for each piece of text with different styling
      let blabla = document.createElement("span"); 
      blabla.innerText = 'BlaBla:' 
      blabla.style = 'color:yellow'
    
      let text = document.createElement("span");
      text.innerText = `sometextssometextssometextssometextssometexts` 
    
      // Append both span elements to the paragraph where word spacing should
      // be applied
      let name = document.createElement("p");      
      name.appendChild(blabla);
      name.appendChild(text);
      
      document.querySelector('.main').appendChild(name)
    })
    .main {
      position: relative;
      width: 250px;
      height: 140px; 
      background-color: gray;
    }
    
    p {
      position: relative;
      margin-top:0;
      display:block;
      color:white;
    }
     
    span {     
      overflow-wrap: break-word;
    }
    <div class="main" id="main0"></div>