Páginas

Sunday, September 18, 2011

Dynamic HTML container size with CSS + JS

Have you ever tried to make a container (let's say a span) have the size of the text dynamically, without you having to har code it? Here's how I've done it using JavaScript (actually JQuery) and some CSS.

First let's define the markup:

<span id="ruler"></span>
<div class="wrapper">
    <span class="name">Hello World</span>
    <span class="name">I am a very very very very very big string.......................</span>
    <span class="name">I am a normal string</span>
</div>  


The only thing of notice here is the span with the id ruler, this span is empty and is what is going to help us measure the string size in pixels.

Now for the javascript:


String.prototype.visualLength = function() {
    $("#ruler").html(this.toString());
    var width = $("#ruler").width();
    $("#ruler").text("");
    return width;
};

$("span.name").each(function() {
    $(this).css("width", $(this).text().visualLength());
});

This defines a new function for Strings called visualLength that puts the string in the ruler span, gets the width in pixels and cleans it. Then there is an iterator that sets the width for each of the spans we've defined to the one returned by the function.

And that is it. Now we just need some CSS, to make use of this:

span.name{
    display: block;
    border: 3px solid #FF0000; 
    margin-right:auto;
    margin-left:auto;
}    


div.wrapper{
    width: 500px;
    border: 3px solid #000;  



span#ruler{
    visibility: hidden;
    white-space:nowrap;
}  


This code makes the ruler invisible and impedes the text from wrapping. The rest is just an example of how to use this feature to center your text in an outer container. Here is a demo.

Note: The javascript code was based on a blog somewhere, but I cannot seem to find it. If someone knows the link, I'll be happy to refer it.