How to prevent text wrapping
Short answer
white-space: nowrap forbids wrapping text to a new line:
<button style="white-space: nowrap;">Add to cart</button>This is useful for buttons, prices and labels: "Add to" on one line and "cart" on another looks bad.
Only in one spot
To glue two words together, such as a number and its unit, put a non-breaking space between them:
<p style="width: 150px; border: 1px solid silver;">Delivery takes about 5 days and the box weighs 12 kg</p>Even headings
Sometimes you do not need to forbid wrapping, just make it nicer. text-wrap: balance evens out the line lengths so the last line is not left with one word:
<h3 style="width: 260px; text-wrap: balance;">A long heading that would leave one lonely word</h3>For paragraphs there is text-wrap: pretty — it avoids single words at the end.
Common mistake
nowrap on long text: the line overflows its box and creates sideways scrolling. If the text can be long, add ellipsis truncation with overflow: hidden and text-overflow: ellipsis.
Functions used in this recipe
- white-space — How spaces and line breaks in the source are handled and whether lines may wrap.
- text-wrap — How lines are broken: as usual, balanced in length, or avoiding a lonely last word.
- overflow — What to do with content that does not fit into the element.