Font size auto adjust to fit

后端 未结 7 1824
夕颜
夕颜 2020-12-09 09:06

I\'m trying to do what the title says. I\'ve seen that font-size can be a percentage. So my guess was that font-size: 100%; would do it, but no.

7条回答
  •  清歌不尽
    2020-12-09 10:02

    I was looking into this for work and I liked tnt-rox's answer, but I couldn't help but notice that it had some extra overhead that could be cut out.

    document.body.setScaledFont = function(){
        this.style.fontSize = (this.offsetWidth*0.35)+'%';
        return this;
    }
    document.body.setScaledFont();
    

    Cutting out the overhead makes it run a little bit quicker if you add it to an onresize event.

    If you are only looking to have the font inside a specific element set to resize to fit, you could also do something like the following

    window.onload = function(){
        var scaledFont = function(el){
                if(el.style !== undefined){
                    el.style.fontSize = (el.offsetWidth*0.35)+'%';
                }
                return el;
            }
            navs = document.querySelectorAll('.container>nav'),
            i;
        window.onresize = function(){
            for(i in navs){
                scaledFont(navs[i]);
            }
        };
        window.onresize();
    };
    

    I just noticed nicolaas' answer also had some extra overhead. I've cleaned it up a bit. From a performance perspective, I'm not really a fan of using a while loop and slowly moving down the size until you find one that fits.

    function setPageHeaderFontSize(selector) {
        var $ = jQuery;
        $(selector).each(function(i, el) {
            var text = $(el).text();
            if(text.length) {
                var span = $("").css({
                        visibility: 'hidden',
                        width: '100%',
                        position: 'absolute',
                        'line-height': '300px',
                        top: 0,
                        left: 0,
                        overflow: 'visible',
                        display: 'table-cell'
                    }).text(text),
                    height = 301,
                    fontSize = 200;
                $(el).append(span);
                while(height > 300 && fontSize > 10) {
                    height = span.css("font-size", fontSize).height();
                    fontSize--;
                }
                span.remove();
                $(el).css("font-size", fontSize+"px");
            }
        });
    }
    setPageHeaderFontSize("#MyDiv");
    

    And here is an example of my earlier code using jquery.

    $(function(){
        var scaledFont = function(el){
                if(el.style !== undefined){
                    el.style.fontSize = (el.offsetWidth*0.35)+'%';
                }
                return el;
            };
        $(window).resize(function(){
            $('.container>nav').each(scaledFont);
        }).resize();
    });
    

提交回复
热议问题