Jump to content
Jim R

Adjusting font size to fit width of DIV...

Recommended Posts

Posted (edited)

I have 400 dynamically created DIVs, and they each have their own title *school name* *school nickname*.  I don't want them to wrap to a second line, but going nowrap makes the DIV too wide.  I don't want to adjust the font size of all instances, just the 5% which are too long to fit.

I've messed around with vw, but that's obviously impacting all instances.  I'd like to have longer instances have smaller fonts.

Is this possible via CSS?


Edited by Jim R

Share this post

Link to post
Share on other sites

Not with just CSS afaik.  It can be done with javascript by measuring the size of the text at different sizes then applying which ever size fits best.  There's a library for this called FitText.

Share this post

Link to post
Share on other sites

I'll check it out and report back.  


Thank you. 

Share this post

Link to post
Share on other sites
Posted (edited)

This example puts each schoolname into a hidden div and then gets the new width of the div. If it is greater than the std div width (less padding) it reduces the font size.

$schools = [ 'School name one',
             'schoolname one hundred and twenty one',
             'schoolname one thousand one hundred and twenty one',
             'schoolname one million one hundred thousand one hundred and twenty one'     // too long
$output = '';
foreach ($schools as $name) {
    $output .= "<div class='school'>$name</div>" ;
<!DOCTYPE html>
<meta http-equiv="content-language" content="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $().ready( function() {
        $(".school").each( function () {
            var name = $(this).html();
            var wid = $("#tester").css("width");
            if (parseInt(wid) > 380) {
                $(this).css("font-size", "9pt")
<style type="text/css">
    body { font-family: calibri; font-size: 12pt; }
    .school { width: 400px; padding: 10px; border: 1px solid gray; margin: 5px;}
    #tester { white-space: nowrap; display: inline-block; visibility: hidden; }

<div id='tester'></div>



Edited by Barand
  • Like 1

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.