14

I have a textarea that will hold data from a database. It will be disabled so that the user cannot interact with it.

Is there a way to set the height via css so that it fits the area. IE: if there is only one line of text, the textarea height is only 1 row or if there is 3 lines of text, the textarea height is 3 rows?

It's part of an MVC application if that helps at all. I'm using the html.textareafor as well.

tereško
  • 58,060
  • 25
  • 98
  • 150
GarudaLead
  • 469
  • 1
  • 5
  • 18
  • 8
    It sounds like a `textarea` isn't the right fit. You don't want it to be edited and you want it to automatically size. Why not make it another element (`div`,`p`,`ul`,`table`, etc as appropriate). – Tim M. Aug 27 '14 at 02:52
  • 1
    possible duplicate of [Textarea Auto height](http://stackoverflow.com/questions/17772260/textarea-auto-height) – Patrick Aug 27 '14 at 02:52
  • 2
    Thanks Tim. I was so set on using some sort of Control that using a p element didn't even enter in to my mind! – GarudaLead Aug 27 '14 at 03:02

4 Answers4

8

Simplest I can think of is this:

Working Fiddle

div {
   display:inline-block;
   border: solid 1px #000;
   min-height:10px;
   width: 300px;
}

More Options:

Community
  • 1
  • 1
Jatin
  • 3,065
  • 6
  • 28
  • 42
2

More Smart Solution Of Mine depends On Count of Chars :) PHP Laravel

<textarea  class="form-control" name="description" id="description" style="height: {{(strlen($sectionItem->description)/4).'px'}}">{{$sectionItem->description}}</textarea>
Mostafa Mahmoud
  • 153
  • 3
  • 7
1

I do i similar in PHP but i use the rows and not the CSS Attribute:

<textarea class="form-control" type="text" rows="<?= strlen($sometext)/50 ?>" readonly> <?= strip_tags(nl2br($sometext)) ?></textarea>
1

I have spent the last hour reading sites, mostly SO, to find the answer to how to display HTML code on a page without it executing. The best answer I found was to put it in a textarea, but the textarea did not expand vertically to show the entire contents. style='height:auto;' and style='height:fit-content;' did nothing. So, my solution was (so simple it surprised me) - count lines (using '\n', the linefeed character in my text):

        <?php $lines = substr_count($HTML,"\n"); ?>
        <textarea style="border:none;width:100%;" rows="<?=$lines?>" ><?=$HTML?></textarea>

height is now perfect! Add disabled to textarea if you don't want it editable.

Hank Lubin
  • 11
  • 2
  • 1
    This is what the [`
    ` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre) is for.
    – Sean Jan 27 '22 at 18:06