问题
I have a heading. At the end of the last word of the heading is an em dash (there is no white space between the word and the em dash).
When the browser window is made smaller the em dash breaks and goes on to a new line. Having an em dash on its own line is bad typography.
How do I stop the line breaking before the dash (so that the last word runs on to the new line)?
Here is the code:
<h1>XYZ consultancy is super great and brilliant—</h1>
I've tried wrapping the last word and the em dash in a span
with white-space: nowrap;
. It works on my computer, but I can't understand why this is the case as there is no white space and I'm concerned that it won't work on all browsers.
I can't use a non-breaking hyphen, because it needs to be an em dash and I don't think there is a non-breaking em dash.
Thanks
回答1:
This works across browsers:
span { white-space: nowrap }
<h1>XYZ consultancy is super great and <span>brilliant—</span></h1>
You wrote:
I've tried wrapping the last word and the em dash in a
span
withwhite-space: nowrap;
. It works on my computer, but I can't understand why this is the case as there is no white space and I'm concerned that it won't work on all browsers.
You're overthinking it (or taking it too literally). The nowrap
value of the white-space
property prevents text wrapping. That's what it does. Plain and simple.
From MDN:
nowrap
Collapses whitespace as for normal, but suppresses line breaks (text wrapping) within text.
回答2:
If you have complete control over the content of the H1 tag you could wrap the word and em dash in an inline-block span.
<h1>XYZ consultancy is super great and <span style="display:inline-block;">brilliant—</span></h1>
回答3:
You could try using the solution here which is to wrap the text you don't want to break like this:
<h1>XYZ consultancy is super great and <nobr>brilliant—</nobr></h1>
Hopefully that works for you!
回答4:
Create a simple class and pseudo-element that will encapsulate the nowrap, and the symbol. Now you can apply the class to a span on the element:
.emdash {
white-space: nowrap;
}
.emdash::after {
content: "\2014";
}
<h1>XYZ consultancy is super great and <span class="emdash">brilliant</span></h1>
来源:https://stackoverflow.com/questions/44722895/how-to-stop-an-em-dash-from-wrapping-by-itself