子元素相对父元素水平垂直居中布局

本文介绍了三种方法使子元素在父元素中实现水平垂直居中:1) 当子元素宽高确定时,通过设置偏移量实现;2) 利用CSS translate属性;3) 使用绝对定位配合上下左右偏移;4) 采用Flex布局,通过justify-content和align-items属性。

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

一.子div确定宽高
1.根据子div具体大小设置偏移

​ 宽高大小固定的情况下,设置水平和垂直偏移量为父元素的50%。再根据实际长度将子元素向上和向左挪回一半大小

<head>
    <meta charset="utf-8">
    <title>子div水平垂直居中</title>
    <style>
        .father {
            background-color: #e6a1dd;
            width: 600px;
            height: 600px;
            position: relative;
        }

        .child {
            background-color: #df0d1f;
            width: 200px;
            height: 100px;
            margin: auto;
            position: absolute;
            left: 50%;
            top: 50%;
            margin-left: -100px;
            margin-top: -50px;
        }
    </style>
</head>

<body>
    <div class="father">
        father
        <div class="child">
            child
        </div>
    </div>
</body>
效果图

在这里插入图片描述

二.子div不定宽高
1.利用translate
<style>
        .father {
            background-color: #e6a1dd;
            width: 600px;
            height: 600px;
            position: relative;
        }

        .child {
            background-color: #df0d1f;
            margin: auto;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(50%, 50%);
            -webkit-transform: translateX(-50%) translateY(-50%);
        }
    </style>
2.使用绝对定位absolute,再设置上下左右偏移为0
<style>
        .father {
            background-color: #e6a1dd;
            width: 600px;
            height: 600px;
            position: relative;
        }

        .child {
            background-color: #E41627;
            width: 100px;
            height: 100px;
            margin: auto;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;

        }
    </style>
3.使用flex布局父级div设置justify-content:centeralign-items:center
<head>
    <meta charset="utf-8">
    <title>子div水平垂直居中</title>
    <style>
        .father {
            background-color: #b305ad;
            width: 600px;
            height: 600px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .child {
            background-color: #E41627;
            width: 100px;
            height: 100px;

        }
    </style>
</head>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值