将textarea中的文本垂直对齐到普通文本

时间:2018-06-16 22:06:16

标签: html css vertical-alignment

我正在尝试连续创建一个包含2个单元格的表格,第二个单元格包含1行文本区域,以便文本垂直对齐到与第一个单元格中文本相同的级别: picture of desirable result 我注意到,对于FF来说效果不错的CSS在Chrome中失败了(实际上,它还取决于浏览器缩放级别),我需要一种一致的方式来实现它。

为了给MCVE,我创建了这个html:

td, td textarea {
	font-family: serif;
	font-size: 15px;
}
table, tr, td, textarea {
	border: none;
}
td {
	padding-left:	0.5em;
	padding-right:	0.5em;
}
<table><tbody><tr>
    <td>text</td>
    <td><textarea>editable text</textarea></td>
</tr></tbody></table>

<script>
// in the real case, this code is inside a handler of the input event
// which is meant to adjust height when the number of lines is changed
var txt = document.querySelector('textarea');
txt.style.height = '1px';
txt.style.height = txt.scrollHeight+'px';
</script>

正如你所看到的,它并没有像预期的那样工作,但也没有那么多的CSS,所以各种填充依赖于浏览器。现在,我可以想到“修复”这个:为单元格指定垂直填充和vertical-align,为textarea删除padding-top。以下代码段在单独的html中适用于我:< / p>

td, td textarea {
	font-family: serif;
	font-size: 15px;
}
table, tr, td, textarea {
	border: none;
}
td {
	padding: 0 0.5em;
	vertical-align: middle;
}
textarea {
	padding: 0;
}
<table><tbody><tr>
    <td>text</td>
    <td><textarea>editable text</textarea></td>
</tr></tbody></table>

<script>
// in the real case, this code is inside a handler of the input event
// which is meant to adjust height when the number of lines is changed
var txt = document.querySelector('textarea');
txt.style.height = '1px';
txt.style.height = txt.scrollHeight+'px';
</script>

..但它在我的初始上下文中不起作用,而且它在SO片段内也不起作用!是的,为display: block设置textarea会在SO片段中修复此问题:

td, td textarea {
	font-family: serif;
	font-size: 15px;
}
table, tr, td, textarea {
	border: none;
}
td {
	padding: 0 0.5em;
	vertical-align: middle;
}
textarea {
	padding: 0;
	display: block;
}
<table><tbody><tr>
    <td>text</td>
    <td><textarea>editable text</textarea></td>
</tr></tbody></table>

<script>
// in the real case, this code is inside a handler of the input event
// which is meant to adjust height when the number of lines is changed
var txt = document.querySelector('textarea');
txt.style.height = '1px';
txt.style.height = txt.scrollHeight+'px';
</script>

但是还是!这样就可以在SO处完美对齐(垂直“填充”在顶部和底部相同):

enter image description here

但在我原来的背景下并不是那么好:

enter image description here

我很困惑,还有什么可以遗漏?

1 个答案:

答案 0 :(得分:0)

好的,写这篇文章帮助我专注于我所尝试的和我没有尝试过的东西。经过几次迭代(您可以在上面看到)之后,我在textarea中制作了另一个截图并编辑了文本。 textarea的高度得到了调整..这就是全部:唯一缺失的部分是height的{​​{1}}应该等于其textarea,之后对齐是完美的:

enter image description here

Horay!

PS实际上,由于我的scrollHeight没有textarea,因此一旦调整高度,就不需要border位和无效的单元格垂直填充。

PPS更好的是:不是取消填充(我在悬停时使用着色背景,因此零填充看起来不太好),可以改进vertical-align: middle;处理程序以考虑填充:我的初始处理程序是

input

但是使用this suggestion我们可以改为:

var adjustHeightToContent = function()
{
    var defaultHeight = 10;
    var maxHeight = 150;
    jQuery(this).height(defaultHeight); // needed to descrease the height
    jQuery(this).height(Math.min(this.scrollHeight , maxHeight));
};
jQuery('.dataEditor').on('input',adjustHeightToContent);

并且可以使用非零填充。