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 参考资料

相关推荐
会员源码网21 小时前
告别参数混乱:如何优雅解决方法参数过多导致的可维护性难题
css
Lee川2 天前
现代Web开发中的CSS继承、Flexbox布局与LocalStorage交互:从文档解析到实践应用
前端·css
helloweilei3 天前
CSS进阶: background-clip
css
DeathGhost3 天前
CSS container容器查询
前端·css
不会敲代码14 天前
前端组件化样式隔离实战:React CSS Modules、styled-components 与 Vue scoped 对比
css·vue.js·react.js
Sailing4 天前
🚀 别再乱写 16px 了!CSS 单位体系已经进入“计算时代”,真正的响应式布局
前端·css·面试
球球pick小樱花5 天前
游戏官网前端工具库:海内外案例解析
前端·javascript·css
AAA阿giao6 天前
从零构建一个现代登录页:深入解析 Tailwind CSS + Vite + Lucide React 的完整技术栈
前端·css·react.js
掘金安东尼6 天前
用 CSS 打造完美的饼图
前端·css
掘金安东尼6 天前
纯 CSS 实现弹性文字效果
前端·css