Skip to content Skip to sidebar Skip to footer

Font Size Relative To Container

i am designing a site that adjusts itself to the window size, and i need to make the text size relative to it's container (a div). I searched about doing it with css, and found out

Solution 1:

http://jsfiddle.net/AyRMC/

You can use viewport units:

.vw{
    font-size:3vw;
    color:red;
}
.vh{
    font-size:3vh;
    color:green;
}
.vmin{
    font-size:3vmin;
    color:blue;
}

Doesn't have full support quite yet, but IE10, Chrome, Firefox, and Safari all support it.

One downside (or possible upside) is that, at least in chrome, the text doesn't scale as the viewport is resized.

Compatibility: http://caniuse.com/viewport-units

Solution 2:

You should try something like this instead (if I understand correctly what you want to do):

$(".container").each(function(){ //if container is a class
    $('.text', $(this)).css({'font-size': $(this).height()+"px"}); //you should only have 1 #text in your document, instead, use class
});

or something more like this

$(window).resize(function(){
    $('.text').css({'font-size': $('#container').height()+"px"});
});

Solution 3:

If you mean that you are making a responsive site, then you can change the font-size based on document.documentElement.clientWidth inside of the window resize handler.

Also, you can use em units instead of pixels which are scalable and mobile-friendly.

CSS3 also has a new interesting "root em" unit :

CSS3 introduces a few new units, including the rem unit, which stands for "root em". If this hasn't put you to sleep yet, then let's look at how rem works.

The em unit is relative to the font-size of the parent, which causes the compounding issue. The rem unit is relative to the root—or the html—element. That means that we can define a single font size on the html element and define all rem units to be a percentage of that.

http://snook.ca/archives/html_and_css/font-size-with-rem

Solution 4:

Try this:

<scripttype="text/javascript">
    $(document).ready(function() {
        $(window).resize(function() {
            document.getElementById("text").style.fontSize = $(".container").height(); 
            // let container is a class 
        });
    });
</script>

Solution 5:

You can use the .resize() event handler which will only fire when the window is resized

var constant = [Some magic number]    

$(window).resize(function() {
    var fontSize = $(this).height()*$(this).width()*constant;
    $(html).css("font-size",fontSize)
}

Using a constant to calculate the font size based on the new width/height

Post a Comment for "Font Size Relative To Container"