@@ -22,7 +22,7 @@ function findOptimalFontSize( textElement, applyFontSize ) {
2222 const paddingRight = parseFloat ( computedStyle . paddingRight ) || 0 ;
2323 const range = document . createRange ( ) ;
2424 range . selectNodeContents ( textElement ) ;
25-
25+ let maxclientHeight = textElement . clientHeight ;
2626 while ( minSize <= maxSize ) {
2727 const midSize = Math . floor ( ( minSize + maxSize ) / 2 ) ;
2828 applyFontSize ( midSize ) ;
@@ -41,7 +41,17 @@ function findOptimalFontSize( textElement, applyFontSize ) {
4141 // Check if text fits within the element's height.
4242 const fitsHeight =
4343 alreadyHasScrollableHeight ||
44- textElement . scrollHeight <= textElement . clientHeight ;
44+ textElement . scrollHeight <= textElement . clientHeight ||
45+ textElement . scrollHeight <= maxclientHeight ;
46+
47+ // When there are calculated line heights, text may jump in height
48+ // the available space may decrease while the font size decreases,
49+ // making text not fit.
50+ // We store a maximum reference height: the maximum reference element height that was observed
51+ // during the loop to avoid issues with such jumps.
52+ if ( textElement . clientHeight > maxclientHeight ) {
53+ maxclientHeight = textElement . clientHeight ;
54+ }
4555
4656 if ( fitsWidth && fitsHeight ) {
4757 bestSize = midSize ;
0 commit comments