Explain Codes LogoExplain Codes Logo

No line-break after a hyphen

html
responsive-design
best-practices
character-encoding
Anton ShumikhinbyAnton Shumikhin·Dec 22, 2024
TLDR

Stop the text break at a hyphen by applying white-space: nowrap with CSS:

/* Prevent breaks like there's no tomorrow */ .no-break { white-space: nowrap; }

Assign the classy class to your HTML elements:

<!-- A hyphen that respects personal boundaries --> <span class="no-break">non-breaking-word</span>

This CSS trick keeps your hyphenated content on a single line.

Equally important, &#8209; is the non-breaking hyphen alternative for squeezing specific hyphens:

<!-- "ob·sti·nate" hyphen won't go away --> <p>Non&#8209;breakable hyphen here</p>

&#8288; is your safeguard against unexpected line breaks, acting as a line break repellent around a hyphen or other characters. Run multiple browser tests to ensure none flees.

Alternative options with explanations

HTML entity: the non-breaking hyphen

The entity &#8209; is your best friend when a specific hyphen needs to commit to not breaking:

<!-- Hyphen's gripping on for dear life --> Stay&#8209;put hyphenated text.

Banishing breaks with a word joiner

To ensure all characters in a sequence follow hyphen’s suit, encase them with the word joiner, &#8288;:

<!-- All aboard the no-break train --> Word&#8288;-&#8288;joiner in action.

Abandoning obsolete tags

Ditch the <nobr> tag—a trend past its prime. Embrace CSS instead:

<!-- No to <nobr>, yes to CSS --> Avoid using: <nobr>text-to-stay</nobr> <!-- Appreciated but outdated -->

Correct character encoding and DOCTYPE

Start HTML documents equipped with the correct DOCTYPE and character encoding:

<!-- The secret password to the club of awesome webpages --> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8">

Embracing cross-browser harmony

Verify your solution's performance in the pageant of browsers:

<!-- Not all browsers are created equal --> Verify across Chrome, Firefox, Safari, Edge, etc.

Further exploration

For complex usage scenarios involving, say, dynamic or user-generated text, you might need additional scripting solutions or regular expressions.