Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textarea Autoheight CSS

Tags:

html

css

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.

like image 338
GarudaLead Avatar asked Aug 27 '14 02:08

GarudaLead


2 Answers

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>
like image 132
Mischa Mustermann Avatar answered Oct 07 '22 09:10

Mischa Mustermann


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.

like image 30
Hank Lubin Avatar answered Oct 07 '22 10:10

Hank Lubin