Font size auto adjust to fit

2019-01-23 03:39发布

问题:

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.

Here is an example: http://jsfiddle.net/xVB3t/

Can I get some help please?

(If is necesary to do it programatically with js there is no problem)

回答1:

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...



回答2:

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



回答3:

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();
});


回答4:

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.



回答5:

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();


回答6:

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");


回答7:

Here's a way to find the height of the text that you are using. It's simple and only uses javascript. You can use this to adjust your text relative to the height you want.

function getTextHeight(text, fontSize) {
    var numberOfLines = 0;
    var STL = text;
    for(var i = 0; i < STL.length; i++){
    if(STL[i] === '<'){
        try{
            if(STL[i + 1] === 'b' && STL[i + 2] === 'r' && STL[i + 3] === '>'){
                numberOfLines++;
            }
        }
        catch(err){
            break;
        }
    }
    return (numberOfLines + 1) * fontSize;
}