简体   繁体   中英

Reduce font-size when long word overflows horizontally

I have long titles that sometimes slightly overflow the window on small screens, so I made a script that reduces the font-size of the title until it fits its container only when the title overflows its container … It works but I'm sure a lighter solution could be found.

function adaptFontSize(titles) {
    $(titles).each(function() {
        var title = $(this),
            reducedFontSize,
            counter = 0;
        if (title[0].scrollWidth <= title.innerWidth()) { // if title <= container
            title.css('font-size', ''); // remove previously added font-size
        }
        while (title[0].scrollWidth > title.innerWidth() && counter < 20) { // while title > container
            var fontSize = reducedFontSize || parseInt(title.css('font-size')); // current title font-size
            reducedFontSize = Math.floor((fontSize - fontSize / 20) * 100) / 100; // reduce the font-size
            title.css('font-size', reducedFontSize + 'px'); // apply the reduced font-size
            counter++ // counter to limit the loop in case title[0].scrollWidth is not supported
        }
    });
}

or here's a JSFiddle: https://jsfiddle.net/Raoulito/pek7b3mr/12/

My problem comes when I try to apply the script on $(window).resize() . It actually works but I can feel that the process is heavy. It has to work in both ways:

  • reduce the font-size if the title's too wide,
  • increase the font-size when the window gets resized wider, until the title reaches its original font-size .

Here are some of steps I tried but did not manage to achieve:

  • that it does not fire the function all the way through at each pixel the window is resized, but rather wait until it stops resizing.
  • when the window gets resized wider, only target—among the titles which are smaller than the window—the ones that have already been resized and might need to get bigger again.

So I'm looking for a way to fix these, or alternatively for a way of reaching this in a much more efficient way.

You can use the VW unit .

1vw equals 1% of the view width, so it's a simple css only solution which works in all modern browsers.

https://jsfiddle.net/pek7b3mr/8/

 body { margin: 1em; font-family: sans-serif; } div { background-color: yellow; font-size: 5vw; margin-bottom: 1rem; } 
 <div>ABCDEFGHIJKLMNOPQRSTUVWXYZ 012356789</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM