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());
});
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.
1 comment:
Is this the blog you were referring to?
http://blog.mastykarz.nl/measuring-the-length-of-a-string-in-pixels-using-javascript/
Post a Comment