Font size auto adjust to fit

后端 未结 7 1788
夕颜
夕颜 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 09:44

    A bit late but this is how I approach this problem:

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

    The base document font is now set.

    For the rest of your elements in the dom set font sizes as % or em and they will scale proportionately.

    0 讨论(0)
  • 2020-12-09 09:57

    This question might help you out but I warn you though this solves it through jQuery:

    Auto-size dynamic text to fill fixed size container

    Good luck.

    The OP of that question made a plugin, here is the link to it (& download)

    BTW I'm suggesting jQuery because as Gaby pointed out this can't be done though CSS only and you said you were willing to use js...

    0 讨论(0)
  • 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 = $("<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();
    });
    
    0 讨论(0)
  • 2020-12-09 10:07

    here I have a mootools solution:

    Element.implement("fitText", function() {
                    var e = this.getParent();
                    var maxWidth = e.getSize().x;
                    var maxHeight = e.getSize().y;
                    console.log(maxWidth);
                    var sizeX = this.getSize().x;
                    var sizeY = this.getSize().y;
                    if (sizeY <= maxHeight && sizeX <= maxWidth)
                        return;
    
                    var fontSize = this.getStyle("font-size").toInt();
                    while( (sizeX > maxWidth || sizeY > maxHeight) && fontSize > 4 ) {
                        fontSize -= .5;
                        this.setStyle("font-size", fontSize + "px");
                        sizeX = this.getSize().x;
                        sizeY = this.getSize().y;
                    }
                    return this;
                });
    
                $$("span").fitText();
    
    0 讨论(0)
  • 2020-12-09 10:08

    Can't be done with CSS.

    100% is in relation to the computed font-size of the parent element.

    reference: http://www.w3.org/TR/CSS2/fonts.html#font-size-props

    For a jQuery solution look at Auto-size dynamic text to fill fixed size container

    0 讨论(0)
  • 2020-12-09 10:08

    Here is another jQuery solution ...

    /**
     * Resizes page header font-size for the text to fit.
     * basically we add a hidden span into the header,
     * put the text into it and then keep reducing the super large font-size
     * for as long as the height of the span exceeds the super
     * tall line-height set for the test (indicating there is more than one line needed
     * to show the text).
     */
    function setPageHeaderFontSize(selectorString) {
        jQuery(selectorString).each(
            function(i, el) {
                var text = jQuery(el).text();
                var length = text.length;
                if(length) {
                    var id = "TestToSeeLengthOfElement_" + i;
                    jQuery(el).append("<span style='visibility: hidden; width: 100%; position: absolute; line-height: 300px; top: 0; left: 0; overflow: visible; display: table-cell;' id='"+id+"'>"+text+"</span>");
                    var innerEl = jQuery("#"+id);
                    var height = 301;
                    var fontSize = 200;
                    while(height > 300 && fontSize > 10) {
                        height = jQuery(innerEl).css("font-size", fontSize).height();
                        fontSize--;
                    }
                    jQuery(innerEl).remove();
                    jQuery(el).css("font-size", fontSize+"px");
                }
            }
        );
    }
    
    //you can run it like this... using any jQuery enabled selector string (e.g. h1.pageHeaders works fine). 
    setPageHeaderFontSize("#MyDiv");
    
    0 讨论(0)
提交回复
热议问题