如何使用 CSS 将表格放在页面的中心?

新手上路,请多包涵

我正在使用以下代码。如何使用 CSS 将这个表格放在页面的中心?

 <html>
    <head>
        <link rel="stylesheet" type="text/css" href="styles.css" />
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>The Main Page</title>
    </head>
    <body>
        <table>
            <tr>
                <td><button class="lightSquare"></button></td>
                <td><button class="darkSquare"></button></td>
                <td><button class="lightSquare"></button></td>
                <td><button class="darkSquare"></button></td>
                <td><button class="lightSquare"></button></td>
                <td><button class="darkSquare"></button></td>
                <td><button class="lightSquare"></button></td>
                <td><button class="darkSquare"></button></td>
            </tr>
        </table>
    </body>
</html>

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

阅读 431
1 个回答

2022 年编辑:请使用 Flexbox

使用 Flexbox,说明在这里: https ://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container

 .box {
  background-color: red;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 400px;
  width: 400px;
}

.box div {
  background-color: blue;
  width: 100px;
  height: 100px;
}

 <div class="box">
  <div></div>
</div>


2021 年答案保留在下方。

 html, body {
    width: 100%;
}
table {
    margin: 0 auto;
}

示例 JSFiddle

垂直对齐块元素并不是最简单的事情。下面的一些方法。

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

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