CSS
CSS: How to Prevent Line Breaks in Text
In web design, controlling text layout is essential for a clean, consistent user experience. Sometimes, you may want to prevent a line break so that a specific word, sentence, or inline element stays on a single line.
In this blog, we’ll explore:
- ✅ Why you’d want to prevent line breaks
- 🛠️ CSS property to prevent line wrapping
- 🧪 Practical examples
- 🧠 Extra tips for fine-tuned control
✅ Why Prevent Line Breaks?
Preventing line breaks can be helpful when:
- You don’t want a product name or brand to split
- You’re styling buttons or navigation menus
- You’re working with labels, icons, or inline elements that must stay together
- You want to avoid awkward hyphenation in responsive layouts
🛠️ CSS Property: white-space: nowrap
The most direct way to stop text from breaking to a new line is:
white-space: nowrap;
This tells the browser to keep the content on a single line, even if it overflows.
🔧 Example:
.nobr {
white-space: nowrap;
}
<p class="nobr">ThisIsAVeryLongWordThatShouldNotBreak</p>
Result: The paragraph content will stay on one line, and overflow instead of wrapping.
📦 Use Case: Button or Label Text
.button {
white-space: nowrap;
padding: 10px 20px;
}
<button class="button">Do Not Break</button>
This ensures the button text remains on one line regardless of screen size (unless you also control overflow).
✅ Combining with Overflow Handling
If you’re preventing line breaks, you might also want to handle overflow gracefully:
.nobr {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
This combination will hide the overflowing text and show an ellipsis (...
) when the text is too long.
💡 Prevent Breaks Between Words
If you want to prevent breaking between two specific words, use a non-breaking space (
) in HTML:
<span>OpenAI ChatGPT</span>
This ensures “OpenAI” and “ChatGPT” stay on the same line.
🧠 Summary
Goal | CSS or HTML Solution |
---|---|
Prevent line break | white-space: nowrap; |
Hide overflowed content | overflow: hidden; |
Show ellipsis | text-overflow: ellipsis; |
Prevent break between words | in HTML |
📌 Final Thoughts
Using white-space: nowrap
is a simple yet powerful technique in CSS. Whether you’re managing buttons, menus, or any inline text — controlling line breaks can significantly improve your layout and readability.