span word-wrap in list elements

3.2k Views Asked by At

I am trying to have multiple span elements in a list item. They are suppose to be inline of course. When i add the word-wrap: break-word property to one of the span elements, i am expecting the words to wrap, but the element also wrap.

In this fiddle you can clearly see that the span element with class message is behind the element name. I would like these elements inline but with a word wrapping for the second with class message.

What I am trying to achive could be compared to twitch.tv chat messages structure. enter image description here

The twitch.tv HTML for a message is the following:

<li class="ember-view message-line chat-line" id="ember6565">
  <div class="indicator"></div>
  <span class="timestamp float-left">3:34</span> 
  <span class="badges float-left"></span>
  <span class="from" style="color:#D2691E">yourusername</span>
  <span class="colon">:</span> 
  <span class="message" style="undefined">message here</span>
</li>

Regards

3

There are 3 best solutions below

1
On BEST ANSWER

Maybe the following might be what you need.

I added white-space: nowrap to the li elements to keep the inline child elements on one line.

You then need to add white-space: normal to the .message span to keep the break-word-wrapping the way you need it. Remember that white-space is inherited, so you need to reset it to normal for the inline span.

.messages {
  list-style-type: none;
  width: 100px;
  border: 1px dotted blue;
  margin: 0;
  padding: 0;
}
.messages li {
  white-space: nowrap;
}
.messages li .message {
  white-space: normal;
  word-wrap: break-word;
  background-color: tan;
}
<ul class="messages">
  <li>
    <span class="name">wILL</span>
    <span class="message">sakdjfhskdjhfksjahflkjhldkjsakljfhalskdfhqweqweqeqeqweqweqweqweqweqwe</span>
  </li>
</ul>

1
On

Do not add space in between the spans. That is the key. That allows the spans to be inline.

I hope this helps. Check this fiddle

0
On

The issue here is the seriouslyhonkinglongword is being broken after it's been pushed onto the next line. Watch this demonstration closely.

The only quick solution to this would be to add white-space: pre; to the container:

.messages li .message{
    white-space: pre;
}

Remember, the whitespace between the two span tags still classifies as a space node, so it's being treated as though there were a space character between those two span containers.

FYI: I had a hard time finding a satisfactory solution to this issue sometime last year, too.