The element
textarea
has certain irregularity, quite understandable though: you can set it width with CSS style and
width
property (please see
http://www.w3schools.com/cssref/pr_dim_width.asp[
^]), but the best way to set up its height is using the attribute
rows
.
Why? Because this way you define fixed integer (non-fractional) number of rows visible in the area at once, regardless of the font and other presentation detail, which is usually very convenient. Please see:
http://www.w3schools.com/tags/att_textarea_rows.asp[
^].
[EDIT]
That's not all, now you need to determine the required width by the content of each line. You can do it by creating a hidden element and measuring its size. This is explained here:
http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript[
^].
So, here is the conclusion: you have some text. I assume you want to fit it into the text area without wrapping (with wrapping, this is a different problem, also solvable, but this is not what you are asking about, because it would take width on input and produce required height on output, so we need to assume no-wrapping solution). First, you parse the text into lines; the number of lines will give you the value of
rows
. Then you put the text in a hidden
div
and measure required
width
defined by a longest line (longest not in characters, but in pixels, which is not the same). Basically, that's it.
—SA