CSS-实例-div 水平居中 垂直靠上

1 需求


2 语法


3 示例

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表格水平居中、垂直靠上示例</title>
    <style>
        /* 设置包含表格的div样式,使其内容水平居中 */
        .container {
            text-align: center; /* 用于行内或内联元素,但不影响块级元素如表格 */
            display: flex;
            justify-content: center; /* 使用flex布局使块级元素居中 */
            align-items: flex-start; /* 垂直靠上 */
            height: 100vh; /* 设置容器高度为视口高度,以便看到垂直靠上的效果 */
            margin: 0; /* 移除默认边距 */
        }

        /* 表格样式 */
        table {
            border-collapse: collapse; /* 合并边框 */
            margin: 0 auto; /* 上下边距为0,左右自动,使表格在水平方向上居中 */
        }

        th, td {
            border: 1px solid black; /* 添加边框以便查看 */
            padding: 8px; /* 添加内边距 */
        }
    </style>
</head>
<body>

<div class="container">
    <table>
        <caption>标题</caption>
        <thead>
        <tr>
            <th>表头1</th>
            <th>表头2</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td>数据1</td>
            <td>数据2</td>
        </tr>
        <!-- 其他行和列... -->
        </tbody>
    </table>
</div>

</body>
</html>

4 参考资料

相关推荐
feixing_fx14 小时前
选择器的威力——深入理解优先级计算与层叠规则
开发语言·前端·css·前端框架·html
星空17 小时前
html\css\js入门
javascript·css·html
晓得迷路了20 小时前
栗子前端技术周刊第 133 期 - Angular v22、React 编译器 Rust 版、pnpm 11.5...
前端·javascript·css
程序猿小泓21 小时前
2026 前端面试全攻略:手写题、算法与计网/TS 高频考点
前端·javascript·css
小小19922 天前
idea 配置less转化为css
前端·css·less
hhb_6182 天前
Less嵌套避坑:优先级冲突实战解析
前端·css·less
AI视觉网奇2 天前
three教学 3d资产拼接源代码
前端·css·css3
用户059540174462 天前
RAG 记忆层踩坑实录:用户偏好凭空消失,我排查了 4 小时,最后用 LangChain + Chroma 搭了套自动化回归测试
前端·css
何何____2 天前
svg基本图形绘制介绍
前端·css
jnene3 天前
html 时间、价格筛选样式处理
前端·css·html