文本在 1cm x 1cm 单元格中居中
Text centering in a 1cm x 1cm cell
我想创建一个包含 3 个单元格的 table。第二个单元格必须居中,宽度为 1 厘米,高度为 1 厘米。第二个单元格中的文本必须 horizontally/vertically 居中:
我几乎成功了,但即使经过多次尝试,我也绝对无法让文本出现在第二个单元格的中间:
<table>
<tr>
<td style="width:50%;"></td>
<td style="min-width:1cm;max-width:1cm;border:none">
<div style="min-height:1cm;max-height:1cm;background-color:red">
<span class="PageNumber">1</span>
</div>
</td>
<td style="width:50%;"></td>
</tr>
</table>
我怎样才能让 span
占据完整的 div
容器以使文本(垂直和水平)居中?
注意:实际代码更复杂,我刚刚提取了导致问题的部分(在 1x1 厘米单元格中居中文本)。
<table>
<tr>
<td style="width:50%;"></td>
<td style="min-width:1cm;max-width:1cm;border:none">
<div style="display:inline-block;min-height:1cm;max-height:1cm;background-color:red">
<div style="margin:0 auto;vertical-align:middle;">
<span class="PageNumber">1</span>
</div>
</div>
</td>
<td style="width:50%;"></td>
</tr>
</table>
TL:DR:
我在您的 div 中创建了一个 div,因此 margin: 0 auto
将使其水平居中,而 display
样式将使其垂直居中。
关于 CSS 居中的更多信息:https://www.w3.org/Style/Examples/007/center.html
除了表格只能用于表格数据之外,您还可以使用 display:flex
:
实现您想要的效果
.number {
display: flex;
min-height: 1cm;
max-height: 1cm;
background-color: red;
align-items: center;
justify-content: center;
}
<table>
<tr>
<td style="width:50%;"></td>
<td style="min-width:1cm;max-width:1cm;border:none">
<div class="number">
1
</div>
</td>
<td style="width:50%;"></td>
</tr>
</table>
我想创建一个包含 3 个单元格的 table。第二个单元格必须居中,宽度为 1 厘米,高度为 1 厘米。第二个单元格中的文本必须 horizontally/vertically 居中:
我几乎成功了,但即使经过多次尝试,我也绝对无法让文本出现在第二个单元格的中间:
<table>
<tr>
<td style="width:50%;"></td>
<td style="min-width:1cm;max-width:1cm;border:none">
<div style="min-height:1cm;max-height:1cm;background-color:red">
<span class="PageNumber">1</span>
</div>
</td>
<td style="width:50%;"></td>
</tr>
</table>
我怎样才能让 span
占据完整的 div
容器以使文本(垂直和水平)居中?
注意:实际代码更复杂,我刚刚提取了导致问题的部分(在 1x1 厘米单元格中居中文本)。
<table>
<tr>
<td style="width:50%;"></td>
<td style="min-width:1cm;max-width:1cm;border:none">
<div style="display:inline-block;min-height:1cm;max-height:1cm;background-color:red">
<div style="margin:0 auto;vertical-align:middle;">
<span class="PageNumber">1</span>
</div>
</div>
</td>
<td style="width:50%;"></td>
</tr>
</table>
TL:DR:
我在您的 div 中创建了一个 div,因此 margin: 0 auto
将使其水平居中,而 display
样式将使其垂直居中。
关于 CSS 居中的更多信息:https://www.w3.org/Style/Examples/007/center.html
除了表格只能用于表格数据之外,您还可以使用 display:flex
:
.number {
display: flex;
min-height: 1cm;
max-height: 1cm;
background-color: red;
align-items: center;
justify-content: center;
}
<table>
<tr>
<td style="width:50%;"></td>
<td style="min-width:1cm;max-width:1cm;border:none">
<div class="number">
1
</div>
</td>
<td style="width:50%;"></td>
</tr>
</table>