设置表格内文本区域的高度

Setting the height of a textarea inside a table

本文关键字:高度 区域 文本 表格 设置      更新时间:2023-09-26

我已经将文本区域的高度设置为500%,但由于某些原因,它没有更改为500%。我认为这与它在桌子里有关,但我不确定该改变什么来正确设置高度。由于某些原因,表格内文本区域的宽度可能会发生变化。

table,td {
border: 1px solid black;
}
textarea {
resize: none;
width: 100%;
height: 500%;
}
<table> 
<tr>
<td> 
firstTD 
</td> 
<td>
<form method = 'POST' action = 'updateProfile.php'>
<textarea id = 'textarea' placeholder = 'type something here...' onfocus = '"this.placeholder = '''" onblur = '"this.placeholder = 'type something here...''" maxlength = '10000'></textarea>
</form>
</td>
</tr> 
</table>

另一个答案解决了这个问题,但并没有解释它。当你在CSS中使用%来定义width/height时,你会使它成为该元素容器的width/high的任意%。

当您将文本区域设置为100%的空<td>时,它不会很大。

如果没有定位祖先元素,则将其设置为position:absolute将起作用。一个更简单的方法是只使用%以外的东西来定义你的宽度和高度。尝试width:10em;并调整它,直到您得到正确的结果。

编辑

回答评论中的一个问题:在这种情况下,使用%定义高度的原因是因为空单元格有高度,但没有宽度。空表单元格仍然继承行的高度,该行的高度与最高的<td>一样高。在这种情况下,存在另一个具有内容的<td>,从而为单元格提供高度。

所以,如果有另一行,并且同一列中的一个单元格有内容,那么宽度也可以使用%。

也就是说,在表格中使用%表示宽度和高度不是一个好主意,因为当表格中的内容发生变化时,百分比也会发生变化。此外,当使用%而不是px或em时,它不会拉伸父容器。

再次编辑

老实说,我甚至没有注意到form元素。那么百分比是相对于表单元素的高度/宽度的,而不是相对于<td>的。必须有一些填充来提供单元格的宽度/高度,但表单没有任何尺寸。

尝试将position: absolute设置为textarea,并给父级一个position: relative。还去除width,并将leftright的值作为0。但请记住,这将使textarea溢出内容。这就是你所期望的吗?

table,
td {
  border: 1px solid black;
  position: relative;
  width: 350px;
}
textarea {
  resize: none;
  height: 500%;
  left: 0;
  right: 0;
  position: absolute;
  top: 0;
}
<table>
  <tr>
    <td>
      firstTD
    </td>
    <td>
      <form method='POST' action='updateProfile.php'>
        <textarea id='textarea' placeholder='type something here...' onfocus=' "this.placeholder = '''" onblur=' "this.placeholder = 'type something here...''" maxlength='10000'></textarea>
      </form>
    </td>
  </tr>
</table>

或者如果你需要这样的东西?

table,
td {
  border: 1px solid black;
  position: relative;
  width: 350px;
}
textarea {
  resize: none;
  height: 10em;
  width: 100%;
  display: block;
  box-sizing: border-box;
}
<table>
  <tr>
    <td>
      firstTD
    </td>
    <td>
      <form method='POST' action='updateProfile.php'>
        <textarea id='textarea' placeholder='type something here...' onfocus=' "this.placeholder = '''" onblur=' "this.placeholder = 'type something here...''" maxlength='10000'></textarea>
      </form>
    </td>
  </tr>
</table>

有了这个,您可以设置文本区域的大小

$("textarea").css("height", $("textarea").parent("td").height())
.css("width", $("textarea").parent("td").width())