I have a Div, which dosn’t have fix height or width.
the div will contain some text, the length of string not fix. if the String is too long to fit in the div, the text will appear outside the div, what I need is to know how much maximum length of String the div can contain based on it’s width and height.
I have a Div, which dosn’t have fix height or width. the div will
Share
Unless you are using a fixed width font where all characters are the same width (which is unusual), there is no answer to your question. How many characters fit in a given width depends upon what the characters are as characters like a “W” are much wider than characters like an “i” in all variable width fonts.
If you are using a fixed width font, then you need to measure how wide a character is in the font and font-size and font-style you’re using. You can then simply divide the width you have by the character width and determine how many characters will fit.
It is possible to measure a fixed width font, by creating a div with no margin, padding or border, setting the style to
position: absolute, setting the desired font-family and font-size on it and putting one character in the div. You can then fetch the width of the div by getting it’s offsetWidth.See http://jsfiddle.net/jfriend00/kHHU7/ for a simple example.
Here’s a function that measure’s the width of a character in a fixed width font:
You can see it work here: http://jsfiddle.net/jfriend00/y4eZr/