如何在div中水平居中表格?

新手上路,请多包涵

我有一个 <table> 里面一个 <div> ,使用下面的样式,表格没有居中,为什么?

<div> 中的所有内容不应该像我在 CSS 中设置的那样格式化吗?

HTML

 <div>
  <table></table>
</div>

CSS

 div{
  border: 5px solid white;
  border-radius: 5px;
  margin: auto;
  text-align: center;
}

原文由 gte_ 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 308
2 个回答

您正在 div 上设置 margin: auto ,因此 div 将居中……但是您还保留了 div 作为 width: auto 因此它的容器宽度将与它的容器一样宽(一旦您考虑了边距、填充和边框)。

您在 div 上设置 text-align: center ,因此 div 的 内联 子项将居中,但表格不是内联的,因此它不受影响(某些表格单元格内容可能会受到影响,具体取决于遗产)。

如果你想让桌子居中,那么你必须让桌子本身居中。

 table { margin: auto; }

原文由 Quentin 发布,翻译遵循 CC BY-SA 3.0 许可协议

div 元素是块级的,一个块级元素占据其父容器的整个空间,所以 margin: auto; 默认不产生任何影响。并且 text-align: center; 仅适用于内联级子级,但 table 不是其中之一。

You can set the table as inline table display: inline-table; , so all the inline children including the table will be centered by text-align: center; on the parent div

 div {
  border: 1px solid red;
  text-align: center;
}
table {
  border: 1px solid blue;
  display: inline-table;
}
 <div>
  <table>
    <tr>
      <td>Hello world</td>
    </tr>
  </table>
</div>

原文由 Stickers 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题