在相对 table 单元格中水平居中绝对 div
centering absolute div horizontally in relative table cell
我有 table 个 table 个单元格。在那些 table 单元格中,我想显示一个绝对定位的 div。 div 有一个固定的顶部和底部,我希望它显示在 table 单元格的中心。到目前为止,这是我的代码:
table {
width: 100%;
border: 1px solid;
height: 200px;
table-layout: fixed;
}
table td {
position: relative;
border: 1px solid
}
div {
position: absolute;
top: 20%;
bottom: 30%;
border: 1px solid;
box-sizing: border-box;
padding: 5px;
width: 90%;
margin: auto;
}
<html>
<table>
<tr>
<td>
<div>Content</div>
</td>
<td> </td>
</table>
</html>
我将边距设置为自动,希望它能使 div 居中,但它没有。由于页面外观的其他要求,我必须在其中包含 table-layout 并且我无法设置 td 的宽度。
谁能告诉我我做错了什么?
由于您为绝对定位的元素指定了宽度,因此您只需添加 left: 0; right: 0;
即可使其水平居中。
或者,由于该元素具有固定的、基于百分比的宽度 90%
,您也可以只使用 left: 5%
将其水平居中。
table {
width: 100%;
border: 1px solid;
height: 200px;
table-layout: fixed;
}
table td {
position: relative;
border: 1px solid
}
div {
position: absolute;
top: 20%;
bottom: 30%;
left: 0; right: 0;
border: 1px solid;
box-sizing: border-box;
padding: 5px;
width: 90%;
margin: auto;
}
<html>
<table>
<tr>
<td>
<div>Content</div>
</td>
<td> </td>
</table>
</html>
我有 table 个 table 个单元格。在那些 table 单元格中,我想显示一个绝对定位的 div。 div 有一个固定的顶部和底部,我希望它显示在 table 单元格的中心。到目前为止,这是我的代码:
table {
width: 100%;
border: 1px solid;
height: 200px;
table-layout: fixed;
}
table td {
position: relative;
border: 1px solid
}
div {
position: absolute;
top: 20%;
bottom: 30%;
border: 1px solid;
box-sizing: border-box;
padding: 5px;
width: 90%;
margin: auto;
}
<html>
<table>
<tr>
<td>
<div>Content</div>
</td>
<td> </td>
</table>
</html>
我将边距设置为自动,希望它能使 div 居中,但它没有。由于页面外观的其他要求,我必须在其中包含 table-layout 并且我无法设置 td 的宽度。
谁能告诉我我做错了什么?
由于您为绝对定位的元素指定了宽度,因此您只需添加 left: 0; right: 0;
即可使其水平居中。
或者,由于该元素具有固定的、基于百分比的宽度 90%
,您也可以只使用 left: 5%
将其水平居中。
table {
width: 100%;
border: 1px solid;
height: 200px;
table-layout: fixed;
}
table td {
position: relative;
border: 1px solid
}
div {
position: absolute;
top: 20%;
bottom: 30%;
left: 0; right: 0;
border: 1px solid;
box-sizing: border-box;
padding: 5px;
width: 90%;
margin: auto;
}
<html>
<table>
<tr>
<td>
<div>Content</div>
</td>
<td> </td>
</table>
</html>