为什么不垂直对齐:中间与表格单元中的输入元素一起使用? [英] Why doesn't vertical-align: middle work with input elements in a table-cell?
问题描述
这是我的代码:
* { vertical-align: top; margin: 0; }
td { vertical-align: middle; border: 1px solid red; }
td:nth-child(1) { line-height: 3em; }
td:nth-child(2) { line-height: 4em; }
td:nth-child(3) { line-height: 0.1em; }
p, input { outline: 1px solid green; }
<table>
<tr>
<td>
<p>
Some vertically centered text.
</p>
</td>
<td>
<input type="text">
</td>
<td>
<input type="text">
</td>
</tr>
</table>
正如人们所看到的,p
以及input
和line-height: .1em
垂直居中排列整齐,而input
和line-height: 4em
则移到顶部.
As one can see, the p
is neatly vertically centered, as well as the input
with line-height: .1em
, while the input
with line-height: 4em
is moved to the top.
经过长时间的研究,我没有找到关于这种行为的解释.
I did not find an explanation for this behaviour after lengthy research.
我设置了一个jsfiddle: https://jsfiddle.net/dlenne/8xapwz11/14/.
I set up a jsfiddle: https://jsfiddle.net/dlenne/8xapwz11/14/.
推荐答案
您已在td
上设置了vertical-align: middle
,每个元素都是input
元素的父级.
You've set vertical-align: middle
on the td
, each of which is a parent of an input
element.
但是vertical-align
属性未继承(源 ).
But the vertical-align
property is not inherited (source).
因此,一种解决方案是将规则直接应用于输入:
So, one solution is to apply the rule directly to the inputs:
* { vertical-align: top; margin: 0; }
td { vertical-align: middle; border: 1px solid red; }
td:nth-child(1) { line-height: 3em; }
td:nth-child(2) { line-height: 4em; }
td:nth-child(3) { line-height: .1em; }
p, input { outline: 1px solid green; }
input { vertical-align: middle; } /* new */
<table>
<tr>
<td>
<p>Some vertically centered text.</p>
</td>
<td>
<input type="text">
</td>
<td>
<input type="text">
</td>
</tr>
</table>
另一种解决方案是通过将输入的display
值从inline
切换到block
来绕过line-height
规则.
An alternative solution simply bypasses the line-height
rules by switching the display
value of the inputs from inline
to block
.
* { vertical-align: top; margin: 0; }
td { vertical-align: middle; border: 1px solid red; }
td:nth-child(1) { line-height: 3em; }
td:nth-child(2) { line-height: 4em; }
td:nth-child(3) { line-height: .1em; }
p, input { outline: 1px solid green; }
input { display: block; } /* new */
<table>
<tr>
<td>
<p>Some vertically centered text.</p>
</td>
<td>
<input type="text">
</td>
<td>
<input type="text">
</td>
</tr>
</table>
参考:
- 了解
vertical-align
或如何(不)垂直居中显示内容" - 10.8.1领先和半领先(W3C定义对于
line-height
和vertical-align
) - 行高继承
- Understanding
vertical-align
, or "How (Not) To Vertically Center Content" - 10.8.1 Leading and half-leading (W3C definitions for
line-height
andvertical-align
) - Line-height inheritance
这篇关于为什么不垂直对齐:中间与表格单元中的输入元素一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!