Search code examples
cssoverflowcss-float

break-word (not break-all) in container with floating child in Firefox


A text with overflow-wrap: break-word side by side with a float element works nicely in Chrome but Firefox doesn't word break as expected, it doesn't take the floating element's width into account.

Screenshot from chrome (this is the desired output)

The long word 'Antiestablishmentarianism' is broken since it can't fit the available space - other words that do fit remain intact.

Chrome screenshot

Screenshot from the failed rendering in Firefox

The long word isn't broken as expected, instead it's pushed down below the yellow floating element. Some word-breaking is going on - as the last letter m ends up on a separate row. Seems like Firefox can't quite handle word-wrap + the yellow floating element.

FF screenshot

So the question is: Is there any way to make Firefox render the word-break as nicely as Chrome without removing the float element? (I know, I could probably add more HTML wrappers and use flex or something instead - but I'd prefer to keep the current structure)

section {
  width: 400px;
  background: lightblue;
}

section h1 {
  font-size: 30px;
  font-family: Tahoma;
  overflow-wrap: break-word;
}

.yellow-box {
  width: 100px;
  height: 300px;
  float: right;
  background: yellow;
}
   
<section>
  <span class="yellow-box"></span>
  <div>
    <h1>
      Gotta say Antiestablishmentarianism is quite a long word indeed
    </h1>
  </div>
</section>

PS: I don't wanna use break-all because it'll break more words than necessary

But the interesting thing is that if you use word-break: break-all; in Firefox it works perfectly and the floating element's width IS taken into consideration

Screenshot using break-all

As you can see the word 'indeed' is also broken, which is not OK

word-break: break-all in FF

All screenshots in this post were taken using Chrome 114 and FF 114


Solution

  • Since the .yellow-box is floating, you have to reset the BFC of h1 so it doesn't lay under the floating box. see: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Block_formatting_context

    section {
      width: 400px;
      background: lightblue;
    }
    
    section h1 {
      font-size: 30px;
      font-family: Tahoma;
      overflow-wrap: break-word;
      overflow:hidden; /* BFC */
    }
    
    .yellow-box {
      width: 100px;
      height: 300px;
      float: right;
      background: yellow;
    }
    <section>
      <span class="yellow-box"></span>
      <div>
        <h1>
          Gotta say Antiestablishmentarianism is quite a long word indeed
        </h1>
      </div>
    </section>