Search code examples
htmlcsswhitespaceelementline-breaks

CSS - Only wrap text between elements, NOT characters (can't use a space)


Let's say I have a few <span> elements like this, with no spaces between the elements:

<span>aaaaaaaaaa</span><span>bbbbbbbbbb</span><span>cccccccccc</span>

When rendered in a browser, and is being horizontally "squished", I would like the text to wrap ONLY between elements. So, only the first two examples should be allowed:

1. ✔ No wrapping:

aaaaaaaaaabbbbbbbbbbcccccccccc

2. ✔ Element-only wrapping:

aaaaaaaaaa
bbbbbbbbbb
cccccccccc

3. ❌ Character wrapping (this must not be allowed):

aaaaaaaa
aabbbbbb
bbbbcccc
cccccc

How do I prevent the characters from wrapping in CSS? Normally I'd put a space between the elements to get them to wrap properly, but I can't use spaces in this specific case. I've tried the following, but characters still wrap with this (in Firefox, at least):

<style>
.b{
word-break:break-all;
}
.n{
word-break:normal;
}
</style>

<span class="b"><span class="n">aaaaaaaaaa</span><span class="n">bbbbbbbbbb</span><span class="n">cccccccccc</span></span>

Solution

  • I think what you're looking for is white-space: nowrap (which will prevent wrapping within a single .n element), combined with display: inline-block (which will render the elements as inline block-level elements):

    .n {
      white-space: nowrap;
      display: inline-block;
    }  
    <span class="b">
      <span class="n">aaaaaaaaaa</span><span class="n">bbbbbbbbbb</span><span class="n">cccccccccc</span>
    </span>

    This will render the elements beside each other if there is room, or wrap them if there isn't enough room, however no wrapping is allowed within a single .n element.

    On a side note, I suggest using more descriptive class names. This will become a nightmare to maintain very quickly.