Full Byte Developer.

One CSS line fixes the long link that breaks mobile layout

overflow-wrap: anywhere lets a flex item shrink past its content width.

Published here · 3 sources

One pasted link made a page scroll sideways on a phone. One CSS line fixed it.

The problem

A comment with a 120 character link, in a flex row next to an avatar, on a 375 px wide phone screen (Chrome 156, phone emulation). The page grew to 757 px and panned 382 px sideways.

The fix

css
.comment {
  overflow-wrap: anywhere;
}

Measured widths

RuleWidth
no rule757 px (broken)
overflow-wrap: break-word757 px (still broken in flex row)
overflow-wrap: anywhere375 px (fixed)
break-word plus min-width: 0375 px (also fixed)

Why break-word failed

In a flex or grid item, min-width: auto means the box will not go narrower than its min-content size. MDN: with anywhere, the extra break points "are considered when calculating min-content intrinsic sizes". With break-word they are "NOT considered". So the box cannot shrink and the link pushes the page wide. In a plain block, break-word worked fine (375 px).

The check

Paste in the console:

javascript
document.documentElement.scrollWidth > document.documentElement.clientWidth

true = still sideways. false = fixed.

Tip: on phone emulation, window.innerWidth grew to 757 with the page, so scrollWidth > innerWidth said false on the broken page. Compare with clientWidth instead.

Browser support

overflow-wrap: anywhere works in Chrome 80+, Firefox 65+ and Safari 15.4+ (MDN compat data). On older Safari, break-word plus min-width: 0 is the fallback.

Send this to the friend whose page scrolls sideways on phones because of one long link.

Keep this guide

By Full Byte Developer

Filed under Dev tools

Questions about this guide

Why does break-word fail in a flex row?

In a flex item, min-width: auto prevents the box from going narrower than its min-content size. MDN: with anywhere, extra break points are considered when calculating min-content sizes. With break-word they are not.

What is the Safari fallback?

break-word plus min-width: 0 works in older Safari where anywhere is not supported.

Sources

  1. MDN: overflow-wrapdeveloper.mozilla.org
  2. MDN: min-widthdeveloper.mozilla.org
  3. MDN: Element.clientWidthdeveloper.mozilla.org

Next in this stack