24

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)

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
Diego
  • 16,436
  • 26
  • 84
  • 136
  • 2
    Thanks. Here it is for anyone who'd like to see it: http://jsfiddle.net/xVB3t/2/ – Diego Dec 10 '10 at 13:06
  • 1
    thank you very much fot sharing the solved problem, that is really helpful and is how things should be done +1! – Trufa Dec 10 '10 at 13:57
  • possible duplicate of [Auto-size dynamic text to fill fixed size container](http://stackoverflow.com/questions/687998/auto-size-dynamic-text-to-fill-fixed-size-container) – Chris Baker Dec 09 '14 at 17:24
  • 1
    @ChrisBaker The linked question is asking about jQuery, this question isn't, so I wouldn't tag it as a duplicate. – Peter Olson Dec 09 '14 at 19:05
  • 1
    @PeterOlson Considering that the entire content of the accepted answer links to that answer, and without the links this accepted answer would be 100% useless, this is a perfect example of a question that should be marked as a duplicate. Otherwise, this is a good example of "Your Answer is in Another Castle", which is a problem to be avoided and eliminated whenever you see it. – Chris Baker Dec 09 '14 at 19:40
  • Anyone looking for this information should read this related thread: [Font scaling based on width of container](http://stackoverflow.com/questions/16056591/font-scaling-based-on-width-of-container) – Yogi May 30 '15 at 23:48

7 Answers7

16

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

Community
  • 1
  • 1
Trufa
  • 39,971
  • 43
  • 126
  • 190
  • I did a summery of that answer actually here: http://stackoverflow.com/questions/4371003/dynamically-resize-text-to-fill-div/4371117#4371117 – Trufa Dec 10 '10 at 12:57
5

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

Community
  • 1
  • 1
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
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();
});
Eeems
  • 69
  • 3
1

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.

tnt-rox
  • 5,400
  • 2
  • 38
  • 52
0

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();
Karl Adler
  • 15,780
  • 10
  • 70
  • 88
0

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

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;
}
Launch9
  • 26
  • 1
  • 3