问题
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.
回答1:
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>
回答2:
Two different ways to break up words:
.one {
word-break: break-all
}
.two {
word-wrap: break-word;
}
<div style="width:56mm; font-family:Arial; border: 2px solid tomato; background: gold;">
<b>word-break: break-all:</b>
<p>Your selected shipping was <span class=one>UK_RoyalMailSecondClassStandard</span>.</p>
<p>Your selected shipping was <span class=one>Signed For 1st Class</span>.</p>
<b>word-wrap: break-word:</b>
<p>Your selected shipping was <span class=two> UK_RoyalMailSecondClassStandard</span>.</p>
<p>Your selected shipping was <span class=two>Signed For 1st Class</span>.</p>
</div>
来源:https://stackoverflow.com/questions/35378970/word-break-prefer-normal-but-if-not-possible-break-all