宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取
一、使用CSS 居中
在CSS 中设置margin: auto;属性来让table 水平居中。
<style>
table {
margin: auto; /* 居中 */
border-collapse: collapse; /* 折叠边框 */
}
</style>
这里的border-collapse: collapse;是为了让边框线条整齐,不重叠。
二、使用HTML 居中
使用<center>标签来让table 居中,虽然已经过时了但是还是可以使用的。
<center>
<table>
<tr>
<th>表头 1</th>
<th>表头 2</th>
</tr>
<tr>
<td>内容 1</td>
<td>内容 2</td>
</tr>
</table>
</center>
三、使用JavaScript 居中
使用JavaScript 计算table 的宽度,再通过设置margin-left 和margin-right 来让其水平居中。
<script>
var table = document.getElementsByTagName('table')[0];
var marginLeft = -(table.offsetWidth / 2) + 'px';
table.style.marginLeft = marginLeft;
table.style.marginRight = marginLeft;
</script>
四、结合媒体查询实现响应式居中
在不同设备上,table 的宽度会有所不同,使用媒体查询来动态计算marginLeft。
<style>
table {
border-collapse: collapse;
margin: auto; /* 作为基础 */
max-width: 100%; /* 不超过可视区域宽度 */
}
@media screen and (min-width: 768px) {
/* 在宽度大于等于768px 的屏幕上居中 */
table {
margin-left: calc(50% - 384px); /* 需要居中的table 宽度为768px */
margin-right: calc(50% - 384px);
}
}
</style>
五、使用flex 属性居中
将容器(display: flex;)的justify-content 属性设置为center来让table 横向居中。
<div style="display: flex; justify-content: center;">
<table>
<tr>
<th>表头 1</th>
<th>表头 2</th>
</tr>
<tr>
<td>内容 1</td>
<td>内容 2</td>
</tr>
</table>
</div>
最新评论