div的水平垂直居中

本文介绍了div实现水平垂直居中的四种方法:1) 使用flex布局;2) 父元素定位,子元素绝对定位;3) 子元素绝对定位,边距自动;4) 子元素设置左右上角外边距为父元素宽高的一半。

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

div水平垂直居中的方法多种多样
图示:
在这里插入图片描述下面展示一些 内联代码片

<body>
    <div id="parent">
        <div id="child"></div>
    </div>
</body>

方法一:使用flex布局

 <style>
        * {
            margin: 0;
            padding: 0;
        }

        #parent {
            width: 400px;
            height: 400px;
            background-color: aqua;
            margin: 0 auto;
            display: flex;
            justify-content: space-around;
            align-items: center;
        }

        #child {
            width: 200px;
            height: 200px;
            background-color: bisque;

        }
    </style>

方法二:在父元素设置定位元素,在子元素使用绝对定位,相对于父元素进行定位,设置top和left属性,可以使用经过计算后的值或者百分比。

<style>
        * {
            margin: 0;
            padding: 0;
        }

        #parent {
            width: 400px;
            height: 400px;
            background-color: aqua;
            margin: 0 auto;
            position: relative;

        }

        #child {
            width: 200px;
            height: 200px;
            background-color: bisque;
            position: absolute;
            /* top: 100px;
            left: 100px; */
            top: 25%;
            left: 25%;

        }
    </style>

方法三:在子元素使用绝对定位元素,设置top,left,right,bottom的值为0,margin:auto;

 <style>
        * {
            margin: 0;
            padding: 0;
        }

        #parent {
            width: 400px;
            height: 400px;
            background-color: aqua;
            margin: 0 auto;
            position: relative;

        }

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

        }
    </style>

方法四:设置子元素的margin-left和margin-top的值,计算父元素的宽高减去子元素的宽高/2。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值