css - 水平垂直居中

本文介绍了几种常用的CSS水平垂直居中布局方法,包括使用绝对定位结合transform、inline-block结合text-align与table-cell、flex布局等,并附带了示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考:CSS常见布局及解决方案
把简单做好也不简单-css水平垂直居中

1、父节点:relative + 子节点:absolute + transform

<html>
<head>
    <meta charset="utf-8">
    <style type="text/css">
        .parent {
            background-color: #0eabdf;
            width: 300px;
            height: 300px;

            position: relative;
        }

        .child {
            background-color: #fe6464;

            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }
    </style>
</head>

<body>
<div class="parent">
    <div class="child">child</div>
</div>
</body>
</html>

绝对定位脱离文档流,不会对后续元素的布局造成影响。
transform 为 CSS3 属性,有兼容性问题

效果图:

这里写图片描述

2. inline-block + text-align + table-cell + vertical-align

<html>
<head>
    <meta charset="utf-8">
    <style type="text/css">
        .parent {
            background-color: #0eabdf;
            width: 300px;
            height: 300px;

            text-align: center;
            display: table-cell;
            vertical-align: middle;
        }

        .child {
            background-color: #fe6464;

            display: inline-block;
        }
    </style>
</head>

<body>
<div class="parent">
    <div class="child">child</div>
</div>
</body>
</html>

兼容性好

效果图:

这里写图片描述

3. flex + justify-content + align-items

<html>
<head>
    <meta charset="utf-8">
    <style type="text/css">
        .parent {
            background-color: #0eabdf;
            width: 300px;
            height: 300px;

            display: flex;
            justify-content: center; /* 水平居中 */
            align-items: center; /*垂直居中*/
        }

        .child {
            background-color: #fe6464;
        }
    </style>
</head>

<body>
<div class="parent">
    <div class="child">child</div>
</div>
</body>
</html>

只需设置父节点属性,无需设置子元素
蛋疼的兼容性问题

效果图:

这里写图片描述

4、相对与绝对定位


<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .parent-div {
            width: 100px;
            height: 100px;
            background-color: red;
            position: relative;
        }

        .child-div {
            width: 50px;
            height: 50px;
            background-color: #000;
            position: absolute;
            margin: auto;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
        }
    </style>
</head>
<body>
<div class="parent-div">
    <div class="child-div"></div>
</div>
</body>
</html>

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值