HeadlinesBriefing favicon HeadlinesBriefing.com

Preventing Line Breaks in Code Snippets

Hacker News •
×

The author details a method to prevent awkward line breaks within `<code>` elements on a website, enhancing readability. This technique mirrors the use of non-breaking spaces and hyphens in body text to ensure phrases like “5 cm” or “New York” remain intact.

Previously, the author applied this to body text, but a recent post highlighted the issue in inline code snippets. Examples include code like `(?-u:…)` being split into `(?-` and `u:…)` or `--multiline` becoming `-` and `-multiline`. These breaks, caused by browsers interpreting hyphens and spaces as potential break points, disrupt the clarity of code.

Instead of using non-breaking hyphens which could complicate copy-pasting, a JavaScript solution was implemented. This script identifies short `<code>` elements (up to 15 characters) containing line-breaking characters like hyphens or spaces. It then applies a `nowrap` CSS class to these elements.

The corresponding CSS rule, `code.nowrap {text-wrap: nowrap;}`, instructs browsers to avoid breaking lines within these specific `<code>` blocks. This subtle change, while not strictly necessary, is seen as a significant improvement in the site's typographical quality, particularly for technical content.