Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot get textarea to be 100% height of remaining DIV space

Tags:

html

css

textarea

I need your help. For some reason or another, it appears that my textarea does not want to cooperate. What I would like to do, is to expand its height to 100% of the space left in the DIV per the red arrow depicted below. But maybe I am doing something wrong. Perhaps a fresh set of eyes would great help.

enter image description here

Here is the HTML and CSS in question:

<!DOCTYPE html>

<html>

<head>

<style type="text/css">
.content {
    width: 500px;
    height: 500px;
    border: 1px solid blue;
}
textarea {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
}
</style>


</head>

<body>

<div class="content">

    <div>text here</div>

    <div><textarea></textarea></div>

    <div><input type="button" value="Click Me"/></div>


</div>


</body>

</html>
like image 405
BobbyJones Avatar asked Nov 06 '25 20:11

BobbyJones


1 Answers

The problem is that you set the height of textarea to be 100% of its parent. But its parent has height: auto, so its height depends on its contents. That's a recursive definition.

You can solve it by setting an explicit height to that parent, e.g. 100%. But then the sum of heights of the contents of .content would be more than 100%.

If you know the height of the other contents of .content you can use calc().

But if you want a fluid layout, you should can CSS tables.

.content { display: table }
.content > div { display: table-row }
.content > div:nth-child(2) { height: 100% }

Additionally, some browsers may require absolute positioning in order to take the textarea out-of-flow and thus avoid a recursive definition of the height.

.content {
  width: 500px;
  height: 500px;
  border: 1px solid blue;
  display: table;
  table-layout: fix
}
.content > div {
  display: table-row;
  position: relative;
}
.content > div:nth-child(2) {
  height: 100%; /* As much as possible */
}
textarea {
  position: absolute;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
<div class="content">
  <div>text here</div>
  <div><textarea></textarea></div>
  <div><input type="button" value="Click Me" /></div>
</div>

But better remove the wrapper of textarea and use flexbox:

.content { display: flex; flex-direction: column; }
textarea { flex-grow: 1; }

.content {
  width: 500px;
  height: 500px;
  border: 1px solid blue;
  display: flex;
  flex-direction: column;
}
textarea {
  flex-grow: 1;
}
<div class="content">
  <div>text here</div>
  <textarea></textarea>
  <div><input type="button" value="Click Me" /></div>
</div>
like image 191
Oriol Avatar answered Nov 09 '25 09:11

Oriol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!