Preventing Awkward Line Breaks in Code Snippets with CSS
Preventing line breaks in <code> elements
I recently enhanced my website by preventing awkward line breaks within short code snippets. Instead of manually replacing hyphens, which could alter the code's meaning for copy-paste users, I implemented a script that automatically adds a CSS class to short elements containing spaces or hyphens. This approach ensures that browsers render these snippets on a single line, improving readability without compromising the integrity of the code.
This is the sort of typographical nicety that would be handled by a professional typesetter if I was writing a printed book with a fixed layout, but that’s not how websites work.
- danlitt
You can't parse [X]HTML with regex. Because HTML can't be parsed by regex. Regex is not a tool that can be used to correctly parse HTML.
- pwdisswordfishq
Why even bother with the CSS class? Just apply text-wrap: nowrap; to all <code> elements and dispense with the fragile regex parsing.
- pimlottc
Unfortunately this makes it much harder to read on narrow-width screens (e.g. mobile), where the use must scroll horizontally