Jump to content

Adjusting font size to fit width of DIV...


Jim R

Recommended Posts

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
Link to comment
Share on other sites

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.

<?php
$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>
<html>
<head>
<meta http-equiv="content-language" content="utf-8">
<title>test</title>
<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();
            $("#tester").html(name);
            var wid = $("#tester").css("width");
            
            if (parseInt(wid) > 380) {
                $(this).css("font-size", "9pt")
            }
        })
    })
</script>
<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; }
</style>

</head>
<body>
<div id='tester'></div>
    <?=$output?>
</body>
</html>

 

Capture.PNG

Edited by Barand
  • Like 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.