1

Is there a way to set the font-size dynamically based on the containers size with CSS? At the momentan I'm using the following JS code to achieve this behaviour:

var cubeText = function() {
    var fontSize = parseInt($(".cube.avatar").width());
    fontSizeBig = fontSize/3.5
    fontSizeSmall = fontSize/6;
    console.log(fontSize);
    $(".cube span.big").css('font-size', fontSizeBig);
    $(".cube span.small").css('font-size', fontSizeSmall);
}

This has one big drawback: The test pops in and after the page is loaded resized which gives a very unpleasant "ploping" effect.

2 Answers 2

2

Check out the CSS3 unit vw.

If you need to support other browsers, JavaScript is the only way.

Sign up to request clarification or add additional context in comments.

1 Comment

Also great answer, but the unfortunately, as you said, the support is just not far enough.
1

It wont be possible in CSS, and/or not supported by a lot of browsers. You can have a look at the viewport-relative-lengths but it wont work everywhere...

For the ploping effect, you can use something like the content with the same color as the background for example, or transparency. Demo

​$(document).ready(function(){
   changeFontSize();
    });

function changeFontSize(){
    var fontSize = parseInt($(".cube").width());
    var fontSizeBig = fontSize/10;
    var fontSizeSmall = fontSize/20;
    console.log(fontSize);
    $(".big").css('font-size', fontSizeBig);
    $(".small").css('font-size', fontSizeSmall);
    $(".cube").css('color','#000');
}

You can also use a nice js plugin like this one : http://fittextjs.com/

1 Comment

Thanks for the additional link to the great JS plug-in!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.