Explain Codes LogoExplain Codes Logo

Specifying a preferred line break point in HTML text in a responsive design

html
responsive-design
css
html-structure
Anton ShumikhinbyAnton Shumikhin·Oct 5, 2024
TLDR

Use <wbr> or &shy; within words to specify preferred break points for text wrapping in responsive layouts.

<wbr> - Forces a line break at the specified place when required:

<p>unbreakable<wbr>word</p>

&shy; - A discretionary hyphen that only appears if the word wraps:

<p>unbreakable&shy;word</p>

These techniques help maintain readability without distorting the appearance on any screen.

Guide the visibility and flow

Ensure that certain words or phrases remain visible and strictly grouped together using <span> and CSS:

CSS:

/* "Hey, stay together pals!" queue to our words */ .nowrap { white-space: nowrap; }

HTML:

<p>Keep <span class="nowrap">this together</span> when wrapping.</p>

Beautifully manage word flow and readability across all screen sizes.

Manually directing line breaks

If you are a control freak and desire to break lines at exact places regardless of screen size, employ the <br> tags judiciously.

But remember, with great power comes great responsibility:

<p>Use line<br>breaks wisely.</p> <!-- Spiderman's uncle would be proud -->

Advanced strategies in responsive design

Maintain harmony in responsive design by artfully combining white spaces, inline-block elements, and character entities such as &nbsp; to achieve optimal results:

CSS:

/* "Allow me to display my full width!" declaration */ .block-level { display: inline-block; }

HTML:

<!-- "No breaks within me!" order to our code --> <p>Avoid <span class="block-level">breaks&nbsp;here</span>, flow naturally elsewhere.</p>

Tactfully employ these strategies to tailor your layout's text presentation.

Walkthrough of real-world scenario

Consider an address or a phone number as a real-world example. Bundling them in a <span> with display: inline-block; ensures they fold nicely across various screen sizes:

<address> <!-- "We are a group, respect our space!" group together the address --> <span style="display: inline-block;">123 Main St,</span> <span style="display: inline-block;">Anytown, </span> <span style="display: inline-block;">USA</span> </address>

Confronting challenges

Implementing responsive line breaks can be challenging, especially with different languages or lengthy URLs. Make use of punycode or URL shorteners to maintain the aesthetic. Coding conventions like camelCase or snake_case can also benefit from strategically placed <wbr> tags.