javascriptcsshtmlletter-spacing

Filling div using letter-spacing


The problem I'm having is filling a div with text using letter-spacing. The main issue is, I don't know the width of the div.

First I was thinking using, text-align= justify, but since that I've been running in the dark and got no clue to how to solve this. I'm guessing some scripting magic might do the trick.

An imgur link giving you an idea what I mean:

what I have versus what I want

<div id="container">
 <h1>Sample</h1>
 <p>Another even longer sample text</p>
</div>

Here is a link showcasing an example; JSfiddle.


Solution

  • Based the comment of the poster it seems JavaScript is no problem. Here's a possible approach to solve the problem with jQuery:

    JSFiddle 1

    function dynamicSpacing(full_query, parent_element) {
        $(full_query).css('letter-spacing', 0);
        var content = $(full_query).html();
        var original = content;
        content = content.replace(/(\w|\s)/g, '<span>$1</span>');
        $(full_query).html(content);
    
        var letter_width = 0;
        var letters_count = 0;
        $(full_query + ' span').each(function() {
            letter_width += $(this).width();
            letters_count++;
        });
    
        var h1_width = $(parent_element).width();
    
        var spacing = (h1_width - letter_width) / (letters_count - 1);
    
        $(full_query).html(original);
        $(full_query).css('letter-spacing', spacing);
    }
    
    $(document).ready(function() {
        // Initial
        dynamicSpacing('#container h1', '#container');
    
        // Refresh
        $(window).resize(function() {
            dynamicSpacing('#container h1', '#container');
        });
    });
    

    Update

    Small tweak for when the wrapper gets too small: JSFiddle 2