Jesse Macleod
Jesse Macleod

Reputation: 285

Resize text to totally fill container

I have a div with a fixed height and a fluid width (15% of body width). I want the paragraph text inside to totally fill the div; not overflow and not underfill.

I've tried with jQuery to increment the text size until the height of the paragraph is equal to the height of the container div. At that point, the text should be totally covering the div. The only problem is that font-size increments in 0.5px values. You can't do 33.3px; it has to be either 33.0px or 33.5px. So at 33px, my text is far too short to cover the div, and at 33.5px it overflows.

Does anyone have any ideas on how to remedy this? There are lots of plugins for making text fill the whole width of a container, but not for text that has to fill both the width and height. At least, none that I've seen.

<head>
<style type="text/css">
.box {
    display:block;
    position:relative;
    width:15%;
    height:500px;
    background:orange;
}
    .box p {
        background:rgba(0,0,0,.1); /* For clarity */
    }
</style>
</head>

<body>

<div class="box">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. <br><br>
    Suspendisse varius nibh quis urna porttitor, pharetra elementum nisl egestas. Suspendisse libero lacus, faucibus id convallis sit amet, consequat vitae odio.</p>
</div>

<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
function responsiveText(){
    var i = 0.5;

    do {
        $(".box p").css("font-size",(i) + "px");

        var textHeight          =  $(".box p").height(),
            containerHeight     =  $(".box").height();
        i += 0.5;   

    } while ( textHeight < containerHeight );           // While the height of the paragraph block is less than the height of the container, run the do...while loop.
} responsiveText();


$(window).resize(function(e) {
    responsiveText();
});
</script>
</body>

Text set at 33px. It is too short. Text set at 33px. It is too short.

Text set at 33.5px. It overflows. Text set at 33.5px. It overflows.

Upvotes: 6

Views: 1288

Answers (1)

Jeromy French
Jeromy French

Reputation: 12121

I adjusted your function to use em units instead of px, and adjusted the increment from "0.5" to "0.003".

The preview pane is a little unreliable, so check it out in its own window.

Keep in mind:

  • The larger the increment, the fewer loop iterations (and the less processing).
  • The smaller the increment, the "finer" the adjustment and the result.

Upvotes: 4

Related Questions