shuding / react-wrap-balancer

Simple React Component That Makes Titles More Readable
https://react-wrap-balancer.vercel.app
MIT License
4.01k stars 65 forks source link

Resizing results in inconsistent wrapping state #45

Closed pacocoursey closed 1 year ago

pacocoursey commented 1 year ago
  1. Load page with width: 1200px with Balancer around some wrapping text
  2. Resize window to width: 600px, Balancer correctly reflows the text
  3. Resize window to width: 1200px, Balancer does not restore the previous-best line wrapping calculated in (1)

https://user-images.githubusercontent.com/34928425/221677604-1d010e48-7bd0-47de-9d92-bf519be6c0ae.mp4

shuding commented 1 year ago

Did you use flexbox to center the container (instead of e.g. <p> and text-align: center)? That's unfortunately very sad and hard to support automatically :(

The reason is that if you have a centered child (say a h1) in flexbox, it will not expand automatically but match its minimal content width. And then Balancer creates a span inside that h1 to shrink the content width, the structure looks like this:

<div> ← flex
  <h1>
    <span> ← balancer
      Lorem Ipsum

Let's say that initially the content takes like 100px so both h1 and span are 100px wide. When div gets smaller than 100px, h1 and span will shrink, and Balancer will re-calculate a new width (say 50px) and attach to span. But when div starts to get wider h1 will not grow at all because its child is only 50px wide. Since h1 doesn't grow and this library listens to the container size change, it doesn't do anything: https://share.cleanshot.com/pwtPZv2D.

The advice is to add a width: 100% to the h1 to make sure the container always fill the available space, so Balancer can find the best number between 0 and MAX, as well as listening to MAX's changes.

pacocoursey commented 1 year ago

Makes perfect sense, width: 100% fixes it!