Explain Codes LogoExplain Codes Logo

Denoting a preferred place for a line break

html
responsive-design
css
web-development
Nikita BarsukovbyNikita Barsukov·Oct 6, 2024
TLDR

For line breaks at specific spots in a long word or phrase in HTML, use the <wbr> element at the desired break.

Example:

<p>Extra<wbr>ordinary</p>

Or, apply CSS with word-wrap: break-word; to the containing element to enable breaks within longer words.

CSS example:

.word-wrap { word-wrap: break-word; }
<p class="word-wrap">Extraordinary</p>

<wbr> allows fine control for single words, while CSS gives control over entire text blocks.

Taming line breaks

Unicode and HTML characters

To customize break points, mix Unicode characters and HTML entities:

  • Zero-width space (&#8203;): allows a break point without visible characters.
  • Non-breaking space (&#160; or &nbsp; or U+00A0): a space that does not break.
  • Word joiner (&#8288;): inhibit breaks without an extra space as &nbsp; provides.
  • Non-breaking hyphen (&#8209;): Lets connected words stick, even during line breaks.

Inline magic with CSS

Text within a <span> tagged with specific CSS can enforce line break rules:

  • Avoidwrap class: Use <span class="avoidwrap">...</span> to prevent breaks in the contained text.
    • CSS:
      .avoidwrap { // ✨ not just your average block... ✨ display: inline-block; }
  • CSS white-space property: The nowrap value forbids line breaks within the element.
  • Responsive design: Use display: none; in media queries to introduce or remove elements on different screens.

Tables and pseudo-elements

  • HTML table cells: Table cells naturally keep their contents in one line.
  • Pseudo-elements: The ::before and ::after pseudo-elements in CSS help to add non-printable characters influencing breaks.

Insights on line breaks

Master planned line breaks

You can drop HTML tags and CSS directly into your text to construct deliberate break points:

  • Strategic <wbr> usage: Add <wbr> tags within words to indicate the ideal breakpoints.
  • Smart <span>s: Use spans with display: inline-block; to bind words and encourage line breaks around them.

Dealing with dynamic content

Dynamic or generated content can be handled with JavaScript to control breakpoints:

  • Dynamic wrapping: Use JavaScript at regular intervals to wrap text for line breaks.
  • Responsive breaks: Adjust line breaks based on viewport size using JavaScript combined with CSS media queries.

Test and verify

No one-size-fits-all solution exists. Try, test and consult with the bigger tribe of developers on StackOverflow and have a look at curated documentation.