Font size auto adjust to fit

87,082

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

Solution 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

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

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

Share:
87,082

Related videos on Youtube

Diego
Author by

Diego

I'm 28 years old and I started working as a developer as soon as I graduated ORT high-school technical course of studies. I've been working in software development ever since and I have acquired experience with different kind of teams and projects. I've also worked with some clients on my own as a freelancer. Since the beginning of my tech career, I've wanted to grow as a software architect and I'm proud to say I have. I've mainly worked with .NET web technologies and been in charge of different projects, which led me to becoming the architect of a very large and complex product. After getting my Systems Analyst degree I found a new passion in Information Security, so I studied an Information Security Master's degree at Universidad de Buenos Aires. Although I'm not sure I'd like to work directly at the Security area, I love applying that knowledge to development and I really think that's an underrated profile. Besides being kind of a geek and a techie, I've trained Taekwon-do for a lot of years and I enjoy playing sports like handball, tennis and squash. I also like cooking and, of course, eating!

Updated on July 09, 2022

Comments

  • Diego
    Diego almost 2 years

    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)

    • Diego
      Diego over 13 years
      Thanks. Here it is for anyone who'd like to see it: jsfiddle.net/xVB3t/2
    • Trufa
      Trufa over 13 years
      thank you very much fot sharing the solved problem, that is really helpful and is how things should be done +1!
    • Chris Baker
      Chris Baker over 9 years
    • Peter Olson
      Peter Olson over 9 years
      @ChrisBaker The linked question is asking about jQuery, this question isn't, so I wouldn't tag it as a duplicate.
    • Chris Baker
      Chris Baker over 9 years
      @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.
    • Yogi
      Yogi almost 9 years
      Anyone looking for this information should read this related thread: Font scaling based on width of container
  • Diego
    Diego over 13 years
    Thanks @Gaby, now I understand the font-size with percentage :). But still looking for an answer.
  • Trufa
    Trufa over 13 years
    I did a summery of that answer actually here: stackoverflow.com/questions/4371003/…
  • Gabriele Petrioli
    Gabriele Petrioli over 13 years
    @Diego, updated answer with a link to another answer in SO. @Akinator posted it as well.
  • Liron Harel
    Liron Harel almost 9 years
    so simple, and I was lost in JavaScript solutions. Plain css solved this. thank you.