JoseBazBaz JoseBazBaz - 4 months ago 10
CSS Question

Can I change font size based on the number of letters?


Possible Duplicate:

Auto-size dynamic text to fill fixed size container




I have a box which displays the username. However I found that it can only fit 10 letters - I use the standard
h1
font size.

Is there a way to change the
font-size
according to the number of letters? My usernames range from 3 to 10 characters.

Answer

Please try the code below.

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript">

    $(function() {
        var len_fit = 10; // According to your question, 10 letters can fit in.
        var un = $('#user_name');

        // Get the lenght of user name.
        var len_user_name = un.html().length;
        if(len_fit < len_user_name ){

            // Calculate the new font size.
            var size_now = parseInt(un.css("font-size"));
            var size_new = size_now * len_fit/len_user_name;

            // Set the new font size to the user name.
            un.css("font-size",size_new); 
        }
    });
</script>
</head>
<body>
    <h1 id="user_name">Your Long Name</h1>
</body>

</html>

I hope this could help you.

Comments