@@ -17,11 +17,28 @@ function findOptimalFontSize( textElement, applyFontSize ) {
1717 let maxSize = 2400 ;
1818 let bestSize = minSize ;
1919
20+ const computedStyle = window . getComputedStyle ( textElement ) ;
21+ const paddingLeft = parseFloat ( computedStyle . paddingLeft ) || 0 ;
22+ const paddingRight = parseFloat ( computedStyle . paddingRight ) || 0 ;
23+ const range = document . createRange ( ) ;
24+ range . selectNodeContents ( textElement ) ;
25+
2026 while ( minSize <= maxSize ) {
2127 const midSize = Math . floor ( ( minSize + maxSize ) / 2 ) ;
2228 applyFontSize ( midSize ) ;
2329
24- const fitsWidth = textElement . scrollWidth <= textElement . clientWidth ;
30+ // When there is padding if the text overflows to the
31+ // padding area, it should be considered overflowing.
32+ // Use Range API to measure actual text content dimensions.
33+ const rect = range . getBoundingClientRect ( ) ;
34+ const textWidth = rect . width ;
35+
36+ // Check if text fits within the element's width and is not
37+ // overflowing into the padding area.
38+ const fitsWidth =
39+ textElement . scrollWidth <= textElement . clientWidth &&
40+ textWidth <= textElement . clientWidth - paddingLeft - paddingRight ;
41+ // Check if text fits within the element's height.
2542 const fitsHeight =
2643 alreadyHasScrollableHeight ||
2744 textElement . scrollHeight <= textElement . clientHeight ;
@@ -33,6 +50,7 @@ function findOptimalFontSize( textElement, applyFontSize ) {
3350 maxSize = midSize - 1 ;
3451 }
3552 }
53+ range . detach ( ) ;
3654
3755 return bestSize ;
3856}
0 commit comments