Search code examples
cssword-break

word-break, prefer normal but if not possible break-all


I am creating a very thin page (it's being printed on receipt paper: 56mm wide)

I am trying to display some text (in this case shipping selection). Sometimes this text is normal a number of spaced words, e.g. 'Signed for 1st Class', sometimes it is one long word, e.g. 'UK_RoyalMailSecondClassStandard'. My HTML/CSS doesn't know what the text will be (it's rendered php)

My html is:

<div style="margin: 0px;max-width: 56mm;font-family: Arial;border: 1px solid black;">
  Break-all:
  <p>
    Your selected shipping was <span style="word-break: break-all"> UK_RoyalMailSecondClassStandard</span>.
  </p>

  <p>
    Your selected shipping was <span style="word-break: break-all">Signed For 1st Class</span>.
  </p>

Normal:
  <p>
    Your selected shipping was <span> UK_RoyalMailSecondClassStandard</span>.
  </p>

  <p>
    Your selected shipping was <span>Signed For 1st Class</span>.
  </p>

</div>

As you can see from the above snippet, Signed for 1st Class looks good with word-break normal, but UK_RoyalMailSecondClassStandard is wider than the max-width. For word-brak:break-all UK_RoyalMailSecondClassStandard looks acceptable (well crap but the best I can get) but Signed for 1st Class breaks after the first character.

Is there a way, in CSS without knowing what the shipping text will be, to either: 1) break normal, if possible, otherwise break-all or 2) break normal, but actually enforce the max-width.

I feel like I'm making this more complex than it needs to be, but I'm not sure how to proceed.


Solution

  • Use word-wrap: break-word:

    <div style="margin: 0px;max-width: 56mm;font-family: Arial;border: 1px solid black;">
      break-word:
      <p>
        Your selected shipping was <span style="word-wrap: break-word"> UK_RoyalMailSecondClassStandard</span>.
      </p>
    
      <p>
        Your selected shipping was <span style="word-wrap: break-word">Signed For 1st Class</span>.
      </p>
    </div>